
/*
 * load generic tip box at the position of elem. Needs jQuery.
 */
function tip_box_load(elem, tip_kind, tip_data) {
    var left = elem.offsetLeft;
    var top = elem.offsetTop;
    /* xxx MSIE */
    jQuery("#tip_box_container").load("/tip/tip_box_ajax.php", {"tip_kind":tip_kind,"tip_data":tip_data}, function() {
        jQuery("#tip_box").css({"left":left,"top":top});
        jQuery("#tip_box").show("slow");
    });
}

function tip_box_abort() {
    jQuery('#tip_box').hide('slow');
}


function com_submit()
{
    if(document.getElementById('com_text').value.length == 0)
    {
        alert('Fyll i en kommentar först.')
        return false;
    }
    return true;
}

function alb_passwd_popup(alb_id)
{
    var alb_password_popup_qwe = window.open("alb_passwd_login_id" + alb_id + ".html", "pixbox_alb_passwd_popup", "toolbar=no,top=250,left=70,status=no,menubar=no,scrollbars=no,z-index=10,width=480,height=270,resizable=no");
    alb_password_popup_qwe.focus();
}

var gb_reply_popup_windows=new Array();
function gb_reply_popup(owner, parent)
{
    if(!gb_reply_popup_windows[owner] || gb_reply_popup_windows[owner].closed)
        gb_reply_popup_windows[owner] = window.open('/gb_reply_popup.php?parent='+parent+'&owner='+owner, 'pixbox_gb_reply_usr'+owner, 'toolbar=no,top=250,left=70,status=no,menubar=no,scrollbars=no,z-index=10,width=480,height=270,resizable=yes');
    gb_reply_popup_windows[owner].focus();
}

function gb_new_submit()
{
    if(document.getElementById('gb_message').value.length < 2)
    {
        alert('Skriv ett längre inlägg');
        return false;
    }

    button_disable('gb_new_submit_button');
    return true;
}

function gb_delete_confirm()
{
    return confirm('Radera gästboksinlägget?');
}

function alb_create_validate()
{
    if(document.getElementById('alb_title').value.length < 3)
    {
        alert('Fyll i en titel till albumet. Minst 3 tecken.');
        return false;
    }
    else
    {
        document.getElementById('alb_create_submit').value='Vänta...';
        document.getElementById('alb_create_submit').disabled='disabled';
        return true;
    }
}

function alb_edit_validate()
{
    if(document.getElementById('alb_title').value.length < 3)
    {
        alert('Fyll i en titel till albumet. Minst 3 tecken.');
        return false;
    }
    else
    {
        document.getElementById('alb_edit_submit').value='Vänta...';
        document.getElementById('alb_edit_submit').disabled='disabled';
        return true;
    }
}

function popup(page, name, size)
{
    if(size == 'small')
    {
        width = 200;
        height = 150;
    }
    else
    {
        width = 410;
        height = 230;
    }

    /* Obs! page innehåller GET-parametrar i vissa fall */
    var pixbox_popup = window.open('popup.php?page=' + page, "pixbox_popup_"+name, "toolbar=no,top=300,left=320,status=no,menubar=no,scrollbars=no,z-index=10,width=" + width + ",height=" + height + ",resizable=no");
    pixbox_popup.focus();
}

function verify_email(email) {
    if(email.indexOf("@")==-1 || email.indexOf(" ")!=-1)
        return false;
    else
        return true;
}

function usr_reg_submit() {
    try {
        document.getElementById('usr_email').value = trim(document.getElementById('usr_email').value);
        if(!verify_email(document.getElementById('usr_email').value)) {
            alert('Fyll i din epostadress. Du behöva använda din epost för att aktivera ditt användarkonto senare.');
            return false;
        }

        if(document.getElementById('usr_firstname').value.length == 0) {
            alert('Fyll i ditt förnamn.');
            return false;
        }

        if(document.getElementById('usr_lastname').value.length == 0) {
            alert('Fyll i ditt efternamn.');
            return false;
        }

        if(document.getElementById('usr_kom_id').value == 0) {
            alert('Välj din bostadsort.');
            return false;
        }

        if(!document.getElementById('usr_sex_f').checked && !document.getElementById('usr_sex_m').checked) {
            alert('Välj kön.');
            return false;
        }


        if(document.getElementById('usr_birth_year').value == 0) {
            alert('Ange ditt födelsedatum eller åtminstonde ditt födelseår');
            return false;
        }

        var d = new Date();
        if (d.getFullYear() - document.getElementById('usr_birth_year').value < 14) {
            alert('För att bli medlem på Pixbox behöver du vara minst 14 år.');
            return false;
        }


        if(document.getElementById('usr_nickname').value.length < 3 || document.getElementById('usr_nickname').value.length > 16) {
            alert('Fyll i ett användarnamn mellan 3 och 16 tecken.')
            return false;
        }


        if(document.getElementById('usr_password').value.length < 6) {
            alert('Fyll i ett minst 6 tecken långt lösenord.');
            return false;
        }

        if(document.getElementById('usr_password').value != document.getElementById('usr_password_validate').value) {
            alert('Felaktig bekräftelse av lösenordet.');
            return false;
        }

        if(!document.getElementById('usr_agreement').checked) {
            alert('Du måste acceptera medlemsavtalet för att kunna registrera dig.');
            return false;
        }

        document.getElementById('usr_submit_button').value='Vänta...';
        document.getElementById('usr_submit_button').disabled='disabled';
        return true;
    }
    catch (e) {
        return true;
    }
}

function usr_edit_submit()
{
    if(document.getElementById('usr_firstname').value.length == 0)
    {
        alert('Fyll i ditt förnamn.');
        return false;
    }

    if(document.getElementById('usr_lastname').value.length == 0)
    {
        alert('Fyll i ditt efternamn.');
        return false;
    }

    document.getElementById('usr_email').value = trim(document.getElementById('usr_email').value);
    if(!verify_email(document.getElementById('usr_email').value))
    {
        alert('Fyll i en giltig din epostadress.');
        return false;
    }

    if(document.getElementById('usr_password_new').value.length > 0)
    {
        if(document.getElementById('usr_password_new').value.length < 6)
        {
            alert('För kort lösenord. Minst 6 tecken..');
            return false;
        }

        if(document.getElementById('usr_password_new').value != document.getElementById('usr_password_new_verify').value)
        {
            alert('Felaktig bekräftelse av nytt lösenordet.');
            return false;
        }
    }

    if(document.getElementById('usr_sex').value == 0)
    {
        alert('Välj kön.');
        return false;
    }

    if(document.getElementById('usr_birth_year').value == 0)
    {
        alert('Välj födelseår.');
        return false;
    }

    if(document.getElementById('usr_kom_id').value == 0)
    {
        alert('Välj vart du bor.');
        return false;
    }

    if(!document.getElementById('usr_reg_agreement').checked)
    {
        alert('Du måste acceptera användaravtalet.');
        return false;
    }

    if(document.getElementById('usr_password').value.length == 0)
    {
        alert('Fyll i ditt nuvarande lösenord längst ner.');
        return false;
    }

    if(document.getElementById('usr_email').value != document.getElementById('usr_email_original').value)
    {
        if(!confirm('Eftersom du valt att ändra din e-postadress kommer ditt användarkonto inaktiveras tills du svarat på ett epost som kommer att skickas till din nya epostadress. Fortsätt?'))
            return false;
    }
    return true;
}

function usr_search_submit()
{
    var usr_age_min = parseInt(document.getElementById('srch_age_min').value);
    var usr_age_max = parseInt(document.getElementById('srch_age_max').value);

    if(usr_age_min > usr_age_max)
    {
        alert('Du kan inte söka på en minimumålder som är högre än maximumåldern.');
        return false;
    }

    return true;
}

function usr_passwd_change_submit()
{
    if(document.getElementById('usr_password').value.length < 6)
        alert('För kort lösenord. Minst 6 tecken.');
    else if(document.getElementById('usr_password').value != document.getElementById('usr_password_verify').value)
        alert('Felaktig bekräftelse av nytt lösenordet.');
    else
        return true;

    return false;
}


function lan_update(lan_id_selected, kom_id_selected)
{
    ctry_id = document.getElementById('usr_ctry_id').value;

    document.getElementById('usr_kom_id').options.length = 0;
    document.getElementById('usr_kom_id').options[0] = new Option('Ort/kommun',0);
    document.getElementById('usr_kom_id').options[1] = new Option('Välj län först',0);

    if(ctry_id == 0)
    {
        document.getElementById('usr_lan_id').options.length = 0;
        document.getElementById('usr_lan_id').options[0] = new Option('Län',0);
        document.getElementById('usr_lan_id').options[1] = new Option('Välj land först',0);
    }
    else
    {
        document.getElementById('usr_lan_id').options.length = 0;
        document.getElementById('usr_lan_id').options[0] = new Option('Län',0);

        for(i=1 ; i<kom_array[ctry_id].length ; i++)
        {
            document.getElementById('usr_lan_id').options[i] = new Option(kom_array[ctry_id][i]['name'], kom_array[ctry_id][i]['id']);
        }
    }

    if(lan_id_selected != 0)
    {
        for(i=1 ; i<document.getElementById('usr_lan_id').options.length ; i++)
        {
            if(document.getElementById('usr_lan_id').options[i].value == lan_id_selected)
            {
                document.getElementById('usr_lan_id').options[i].selected = 'selected';
                kom_update(kom_id_selected)
                break;
            }
        }
    }
}

function kom_update(kom_id_selected)
{
    ctry_id = document.getElementById('usr_ctry_id').value;
    lan_id = document.getElementById('usr_lan_id').value;
    lan_i_id = 0;

    if(lan_id != 0)
    {
        //alert('Kör! ctry_id=' + ctry_id + ', lan_id=' + lan_id);
        for(i=1 ; i<=kom_array[ctry_id].length ; i++)
        {
            if(lan_id == kom_array[ctry_id][i]['id'])
            {
                lan_i_id = i;
                //alert('hittat');
                break;
            }
        }
    }

    document.getElementById('usr_kom_id').options.length = 0;
    if(lan_i_id == 0)
    {
        document.getElementById('usr_kom_id').options.length = 0;
        document.getElementById('usr_kom_id').options[0] = new Option('Ort/kommun',0);
        document.getElementById('usr_kom_id').options[1] = new Option('Välj län först',0);
    }
    else
    {
        document.getElementById('usr_kom_id').options[0] = new Option('Ort/kommun',0);

        for(i=1 ; i<kom_array[ctry_id][lan_i_id]['kom'].length ; i++)
        {
            document.getElementById('usr_kom_id').options[i] = new Option(kom_array[ctry_id][lan_i_id]['kom'][i]['name'], kom_array[ctry_id][lan_i_id]['kom'][i]['id']);
        }
    }


    if(kom_id_selected != 0)
    {
        for(i=1 ; i<document.getElementById('usr_kom_id').options.length ; i++)
        {
            if(kom_array[ctry_id][lan_i_id]['kom'][i]['id'] == kom_id_selected)
            {
                document.getElementById('usr_kom_id').options[i].selected = 'selected';
                break;
            }
        }
    }
}

function alb_upload_plugin_submit()
{
    action = "http://"+document.getElementById('upload_hostname').value+"/alb/alb_upload_plugin_submit.php?alb_id="+iu_alb_id+"&pic_censur=";

    if(document.getElementById('pic_censur_0').checked)
    {
        action = action + "0";
    }
    else if(document.getElementById('pic_censur_1').checked)
    {
        action = action + "1";
    }
    else if(document.getElementById('pic_censur_2').checked)
    {
        action = action + "2";
    }
    else
    {
        alert('Välj behörighetsnivå.');
        return false;
    }

    getImageUploader("ImageUploader").setAction(action);
    //getImageUploader('ImageUploader').Send();
    return true;
}

function alb_delete_confirm(alb_id)
{
    if(confirm('Är du säker på att du vill radera albumet samt dess tillhörande bilder?'))
        window.location = "alb/alb_sub.php?action=delete&alb_id=" + alb_id;
    return false;
}

function pm_send_submit()
{
    if(document.getElementById('pm_subject').value.length == 0)
    {
        alert('Fyll i titel.');
        return false;
    }

    button_disable('pm_send_submit_button');
    return true;
}

function usr_del()
{
    if(confirm('Är du säker på att du vill raderas?'))
    {
        document.getElementById('usr_del_submit').value = 'Vänta...';
        document.getElementById('usr_del_submit').disabled='disabled';
        return true;
    }
    else
    {
        return false;
    }
}

function hme_upload_choose_alb_id()
{
    alb_id = document.getElementById('hme_upload_alb_id').value;
    if(alb_id == 0)
    {
        alert('Välja album att ladda upp till');
    }
    else
    {
        window.location = '/?page=alb_upload&alb_id=' + alb_id;
    }
}

function acc_level_owner_change(usr_id, location)
{
    location_tmp = 'acc/acc_submit.php?acc_usr_id=' + usr_id + '&returnUrl=' + location;

    if(document.getElementById('acc_friend_' + usr_id).checked)
        location_tmp += '&acc_friend=1';

    window.location = location_tmp;
}

function pm_list_line_mark(o)
{
    o.className = 'line_marked';
}

function pm_list_line_unmark(o)
{
    o.className = 'line_unmarked';
}

function button_disable(but_id)
{
    document.getElementById(but_id).value = 'Vänta...';
    document.getElementById(but_id).disabled = 'disabled';
}

/*
function tip_preview_update()
{
    s = new String(document.getElementById('tip_preview_raw').innerHTML);
    s = s.replace('[tip_name]', document.getElementById('tip_name').value);
    s = s.replace('[tip_email]', document.getElementById('tip_email').value);
    s = s.replace('[tip_text]', document.getElementById('tip_text').value);
    s = s.replace(/\r|\n|\r\n/g, "<br />");

    document.getElementById('tip_preview').innerHTML = s;
}
*/

var pic_preload_loading = false;
var pic_preload_goto = false;
var pic_preload_goto_url = null;
function pic_preload_click()
{
    if(!pic_preload_loading)
        return true;

    pic_preload_goto = true;
    return false;
}

function pic_preload_loaded()
{
    /*alert('laddad');*/
    pic_preload_loading = false;

    document.getElementById('pic_preload_text').style.visibility = 'hidden';
    if(pic_preload_goto && pic_preload_goto_url!=null)
    {
        window.location = pic_preload_goto_url;
    }
}

function pic_slideshow_toggle()
{
    if(pic_slideshow_running)
        pic_slideshow_stop();
    else
        pic_slideshow_start();
}

function pic_slideshow_start()
{
    setCookie('pic_slideshow_interval', 4);
    pic_slideshow_running = true;
    document.getElementById('pic_slideshow_startstop').innerHTML = 'Stoppa bildspelet';
    pic_slideshow_slide();
}

function pic_slideshow_stop()
{
    setCookie('pic_slideshow_interval', 0);
    pic_slideshow_running = false;
    document.getElementById('pic_slideshow_startstop').innerHTML = 'Starta bildspelet';
}

function pic_slideshow_slide()
{
    if(pic_slideshow_running)
    {
        if(pic_preload_loading)
            setTimeout("pic_slideshow_slide();", 100);
        else
            window.location = pic_slideshow_next_url;
    }
}

function pic_show_options_submit()
{
    if(document.getElementById('pic_show_options').value.substring(0, 6) == 'alert ')
    {
        alert(document.getElementById('pic_show_options').value.substring(6));
        return;
    }

    window.location = document.getElementById('pic_show_options').value;
}

function manageCheckboxes(formblock, name_suffix, whatToDo, checkboxController)
{
    if(whatToDo == null)
    {
        if(checkboxController.checked)
            whatToDo = 'checkAll';
        else
            whatToDo = 'uncheckAll';
    }


    forminputs = formblock.getElementsByTagName('input');

    for(i=0; i<forminputs.length; i++)
    {
        if(forminputs[i].type == 'checkbox')
        {
            if(forminputs[i].name.slice(0, name_suffix.length) == name_suffix)
            {
                switch(whatToDo)
                {
                    case 'checkAll':
                        forminputs[i].checked = true;
                        break;

                    case 'uncheckAll':
                        forminputs[i].checked = false;
                        break;

                    case 'inverseSelection':
                        if(forminputs[i].checked)
                            forminputs[i].checked = false;
                        else
                            forminputs[i].checked = true;
                        break;

                    default:
                        break;
                }
            }
        }
    }
}

function acc_list_checkAllSwitch(upperLower)
{
    if(upperLower == 'upper')
    {
        o = document.getElementById('acc_list_checkAll_upper');
        if(document.getElementById('acc_list_checkAll_lower'))
            document.getElementById('acc_list_checkAll_lower').checked = o.checked;
    }
    else
    {
        o = document.getElementById('acc_list_checkAll_lower');
        if(document.getElementById('acc_list_checkAll_upper'))
            document.getElementById('acc_list_checkAll_upper').checked = o.checked;
    }

    if(o.checked)
    {
        whatToDo = 'checkAll';
    }
    else
    {
        whatToDo = 'uncheckAll';
    }

    manageCheckboxes(document.getElementById('acc_list_form'), 'acc_list_usr_id_', whatToDo, null);
}

function pic_move_submit()
{
    if(document.getElementById('pic_move_to_alb_id').value == 0)
    {
        alert('Välj album du vill flytta bilderna till.');
        return false;
    }

    button_disable('pic_move_submit_button');

    return true;
}

function abuse_new_submit(ses_usr_id)
{
    if(document.getElementById('abuse_descr').value.length == 0)
    {
        alert('Fyll i en beskrivning av problemet');
        return false;
    }

    if(ses_usr_id == 1)
    {
        if(document.getElementById('abuse_reporter_name').value.length == 0)
        {
            alert('Fyll i ditt namn');
            return false;
        }

        if(document.getElementById('abuse_reporter_email').value.length == 0)
        {
            alert('Fyll i din epostadress');
            return false;
        }
    }

    if(document.getElementById('abuse_reporter_phone').value.length == 0)
    {
        alert('Fyll i ditt telefonnummer');
        return false;
    }

    return true;
}

function recruit_submit()
{
    emails_in_form = 6;
    emails_not_empty = 0;


    for(i=0 ; i<emails_in_form ; i++)
    {
        if(document.getElementById('recruit_email_' + i).value.length > 0)
            emails_not_empty++;
    }

    if(emails_not_empty == 0)
    {
        alert('Fyll i åtminstonde en epostadress.');
        return false;
    }

    if(document.getElementById('recruit_text').value.length == 0)
    {
        alert('Skriv in ett meddelande du vill skicka med.');
        return false;
    }

    return true;
}

function alb_edit_pic_censur_submit()
{
    if(document.getElementById('alb_edit_pic_censur').value == -1)
    {
        alert('Välj önskad behörighet för bilderna först.');
        return false;
    }

    button_disabled('alb_edit_pic_censur_submit_button');
    return true;
}

function pic_edit_submit()
{
    var year  = parseInt(document.getElementById('pic_time_year').value);
    var month = parseInt(document.getElementById('pic_time_month').value);
    var day   = parseInt(document.getElementById('pic_time_day').value);
    var hour  = parseInt(document.getElementById('pic_time_hour').value);
    var min   = parseInt(document.getElementById('pic_time_min').value);
    var sec   = parseInt(document.getElementById('pic_time_sec').value);

    if(year!=0 || month!=0 || day!=0)
    {
        if(year >= 2000)
            year = year - 2000;
        else if (year >= 1900) {
            year = year - 1900;
        }
        else {
            // this is completely wrong, but works in most cases.
            year = year - 1800;
        }
        var myDate = new Date(year, month-1, day);

        if(myDate.getYear() != year ||
           myDate.getMonth() != month-1 ||
           myDate.getDate() != day)
        {
            alert('Felaktigt datum');
            return false;
        }


        if(hour<0 || hour>23 || min<0 || min>59 || sec<0 || sec>59)
        {
            alert('Felaktigt angiven tidpunkt.');
            return false;
        }
    }

    return true;
}

// Functions for manage cookies

// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "/") +
    ((domain) ? "; domain=" + domain : '.pixbox.se') +
    ((secure) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function deleteCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

//
//  Examples - Unremark if you want to see how this code works
/*
var expdate = new Date ();
FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now
SetCookie ("ccpath", "http://www.hidaho.com/colorcenter/", expdate);
SetCookie ("ccname", "hIdaho Design ColorCenter", expdate);
SetCookie ("tempvar", "This is a temporary cookie.");
SetCookie ("ubiquitous", "This cookie will work anywhere in this domain",null,"/");
SetCookie ("paranoid", "This cookie requires secure communications",expdate,"/",null,true);
SetCookie ("goner", "This cookie must die!");
document.write (document.cookie + "<br>");
DeleteCookie ("goner");
document.write (document.cookie + "<br>");
document.write ("ccpath = " + GetCookie("ccpath") + "<br>");
document.write ("ccname = " + GetCookie("ccname") + "<br>");
document.write ("tempvar = " + GetCookie("tempvar") + "<br>");
*/



function pic_rate_stars_highlight(color, rate)
{
    var img_src, fillness;

    for(i=1 ; i<=5 ; i++)
    {
        img_src = "/images/pic_rate_star_";
        fillness = rate-i+1;
        if(fillness < 0.25)
            img_src += "grey";
        else if(fillness < 0.5)
            img_src += color+"_1_4";
        else if(fillness < 0.75)
            img_src += color+"_1_2";
        else if(fillness < 1)
            img_src += color+"_3_4";
        else
            img_src += color+"_1";
        img_src += ".gif";

        document.getElementById('pic_rate_star_'+i).src = img_src;
    }
}

function forum_topic_new_submit()
{
    if(document.getElementById('forum_topic_new_forum').value == 0)
    {
        alert('Välj kategori först.');
        return false;
    }
    if(document.getElementById('forum_topic_new_subject').value.length < 5)
    {
        alert('Fyll i en längre rubrik.');
        return false;
    }
    if(document.getElementById('forum_topic_new_subject').value.length > 50)
    {
        alert('Rubriken för lång. Max 50 tecken.');
        return false;
    }
    if(document.getElementById('forum_topic_new_body').value.length < 4)
    {
        alert('Fyll i ett innehåll.');
        return false;
    }

    return true;
}

function forum_reply_submit()
{
    if(document.getElementById('forum_reply_body').value.length < 4)
    {
        alert('Fyll i ett svar.');
        return false;
    }

    return true;
}

function forum_post_edit_submit(is_topic)
{
    if(is_topic)
    {
        if(document.getElementById('forum_post_edit_subject').value.length < 5)
        {
            alert('Fyll i en längre rubrik.');
            return false;
        }
        if(document.getElementById('forum_post_edit_subject').value.length > 50)
        {
            alert('Rubriken för lång. Max 50 tecken.');
            return false;
        }
    }

    if(document.getElementById('forum_post_edit_body').value.length < 4)
    {
        alert('Fyll i ett svar.');
        return false;
    }

    return true;
}

function gb_show_pic_extra(gb, pic)
{
    document.getElementById('gb_pic_extra_img').src = '/images/blank.gif';
    document.getElementById('gb_pic_extra_img').src = document.getElementById('gb_pic_img_url_'+pic).innerHTML;
    document.getElementById('gb_pic_extra_title').innerHTML = document.getElementById('gb_pic_title_'+pic).innerHTML;
    document.getElementById('gb_pic_extra_comments').innerHTML = document.getElementById('gb_pic_comments_'+pic).innerHTML;
    document.getElementById('gb_pic_extra_link').href = '/pic_show_id'+pic+'.html';

    ref_offset = get_pos_offset( document.getElementById('gb_'+gb+'_pic'), document.getElementById('gb_pic_extra') );

    document.getElementById('gb_pic_extra').style.left = (ref_offset[0] - 192/2 - 120/2 + 60)+'px';
    document.getElementById('gb_pic_extra').style.top = (ref_offset[1]-35)+'px';
    //document.getElementById('gb_pic_extra').style.display = 'block';
    document.getElementById('gb_pic_extra').style.visibility = 'visible';
}

function gb_hide_pic_extra()
{
    document.getElementById('gb_pic_extra').style.visibility = 'hidden';
}

function get_pos_offset(ref, match)
{
    ref_offset = [ref.offsetLeft, ref.offsetTop];

    ref_parent_pos = findParentPos(ref);
    match_parent_pos = findParentPos(match);

    parent_offset = [ref_parent_pos[0]-match_parent_pos[0], ref_parent_pos[1]-match_parent_pos[1]];

    return [ (parent_offset[0]+ref_offset[0]), (parent_offset[1]+ref_offset[1]) ];
}


function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

function findParentPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

function pic_show_add_tag()
{
    document.getElementById('tags_add_input').style.display = 'block';
    document.getElementById('tag_list').style.display = 'block';
    document.getElementById('tags_add_heading').style.display = 'none';
    document.getElementById('tags_input_field').focus();
    document.getElementById('tags_input_field').select();
}

function utf8_encode( s )
{
    alert('utf8_encode: '+s);
    return unescape( encodeURIComponent( s ) );
}

function utf8_decode( s )
{
    alert('utf8_decode: '+s);
    return decodeURIComponent( escape( s ) );
}

function com_new_toggle_form()
{
    if(document.getElementById('com_input').style.display == 'none')
    {
        document.getElementById('com_input').style.display = 'block';
        document.getElementById('com_text').focus();
        document.getElementById('com_text').select();
    }
    else
    {
        document.getElementById('com_input').style.display = 'none';
    }
}

function truncate(text, lenMax)
{
    if(text.length <= lenMax)
        return text;
    else
        return text.substring(0, lenMax-2)+'...';
}

function isArray(obj) {
    if(obj.constructor.toString().indexOf("Array") == -1)
        return false;
    else
        return true;
}

function isFunction(obj) {
    if(typeof obj == 'function')
        return true;
    else
        return false;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/**
 * Cleans the content of the DOM node
 */
function cleanNode(node) {
    while(node.firstChild) {
        node.removeChild( node.firstChild );
    }
}

var namespaceSuffix = new Array();
/**
 * Generates an uniqe name prefix for javascript identifiers
 */
function getNamespacePrefix() {
    while(true) {
        var prefix = '';
        for(i=0 ; i<5 ; i++)
            prefix += String.fromCharCode(getRand(97, 122));

        var ok = true;
        for(i=0 ; i < namespaceSuffix.length ; i++) {
            if(prefix == namespaceSuffix[i]) {
                ok = false;
                break;
            }
        }
        if(ok)
            break;
    }
    namespaceSuffix.push(prefix);
    return prefix;
}

function getRand(min, max) {
    var span = (max - min) + 1;
    var randVal =  Math.floor(Math.random()*span);
    return min + randVal;
}

function normalizeDegrees(d) {
    while(d >= 360)
        d = d - 360;
    while(d < 0)
        d = d + 360;
    return d;
}

function xmlEscapeElement(text) {
    return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
}

function xmlEscapeAttribute(text) {
    return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace(String.fromCharCode(34), '&quot;').replace(String.fromCharCode(39), '&apos;');
}

function format_username(id, username, premium, online) {
    var ret = "<span style='white-space: nowrap;'>";
        if(online != null) {
            if($online==true) {
                ret = ret + "<img class='usr_online' src='/images/usr_online_on.gif' width='10' height='10' title='Användaren är inloggad' />";
            } else if(!online) {
                ret = ret + "<img class='usr_online' src='/images/usr_online_off.gif' width='10' height='10' title='Användaren är inte inloggad' />";
            } else if(online) {
                ret = ret + "<img class='usr_online' src='/images/usr_online/"+id+".gif' width='10' height='10' alt='' />";
            }
        }
        url = "/usr_show_id"+id+"_page0_order1.html";
        ret = ret + "<a href='"+url+"' class='nickname'>"+username+"</a>";
        if(premium) {
            url = "/premium";
            ret = ret + "<a class='usr_vip_small' href='"+url+"' style='background-color: transparent;'>";
                ret = ret + "<img src='images/usr_vip_small.gif' width='13' height='12' alt='' title='Premiummedlem' />";
            ret = ret + "</a>";
        }
    ret = ret + "</span>";

    return ret;
}

function urlencode(str) {
    return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}

function urldecode(str) {
    return unescape(str.replace('+', ' '));
}

/*
function format_time(time) {
    return time;
}

function html_escape(text, n2br) {
    if(text == null)
        return null;

    text = text.replace('&', '&amp;').replace(String.fromCharCode(34), '&quot;').replace(String.fromCharCode(39), '&#39;').replace('<', '&lt;').replace('>', '&gt;');
    if(n2br)
        text = text.replace('\r\n', '\n').replace('\n', '<br />');
    return text;
}
*/

function format_monetary(sum) {
    var sumInt = Math.round(sum);
    var sumDec = Math.round( (sum-sumInt)*100 ) / 100;

    if(!sumDec)
        return sumInt+',00';
    else {
        ret = (sumInt+sumDec).toString().replace('.', ',');
        if(sumDec%0.1 == 0)
            ret = ret + '0';
        return ret;
    }
}

function html_color_notation(color) {
    var c = color;
    if(c.red > 255)
        c.red = 255;
    if(c.green > 255)
        c.green = 255;
    if(c.blue > 255)
        c.blue = 255;
    if(c.red < 0)
        c.red = 0;
    if(c.green < 0)
        c.green = 0;
    if(c.blue < 0)
        c.blue = 0;

    var hex;
    var s = '#';
    for(i in c) {
        hex = c[i].toString(16);
        if(hex.length == 1)
            hex = '0'+hex;
        s += hex;
    }

    return s;
}

function login_ssl_fixup(form) {
  if (form.login_ssl.checked)
    form.action = "https://secure.pixbox.se/https/login.php";
  else
    form.action = "login.php";
}
