function get_scaled_size(width, height, max_width, max_height, crop)
{
    if (width <= max_width && height <= max_height && !crop)
        return [width, height];

    if (crop)
    {
        max_width  += SH;
        max_height += SH;
    }
    height *= 1.0;
    width  *= 1.0;
    k = crop ? Math.max(max_width/width, max_height/height) : Math.min(max_width/width, max_height/height);;
    w = Math.floor(width * k);
    h = Math.floor(height * k);
    if (w == 0)
        w = 1;
    if (h == 0)
        h = 1;
    return [w, h];
}

$(document).ready(function() {
    $('ul.sf-menu').superfish(); 
    $('#language').bind('change', function() {
        $.cookie('lang', $(this).val(), {expires:365, path:'/', domain:'.imageshack.us'});
        location.reload();
    });
    $('#searchbutton').bind('click', function(e) { 
        if (jQuery.trim($('#searchfield').val()).length) 
            $('#searchform').submit(); 
    });
    $('#searchfield').bind('keydown', function(e) {
        if (e.which == 13) {
            if (jQuery.trim($('#searchfield').val()).length)
                $('#searchform').submit();
            e.stopPropagation();
            e.preventDefault();
        }
    });
    // Re search form
    $('#searchbutton2').bind('click', function(e) {
        if (jQuery.trim($('#searchfield2').val()).length)
            $('#searchform2').submit();
    });
    $('#searchfield2').bind('keydown', function(e) {
        if (e.which == 13) {
            if (jQuery.trim($('#searchfield2').val()).length)
                $('#searchform2').submit();
            e.stopPropagation();
            e.preventDefault();
        }
    });


    var do_login = function(o) {
        $('#login_dialog .error').hide();
        var user = jQuery.trim($('#l_login').val());
        var pass = jQuery.trim($('#l_password').val());
        var stay = ($('#stay_logged_in').attr('checked')) ? 'true' : '';
        
        if (!user.length) {
            $('#l_no_user_error').show();
            return; 
        }
        if (!pass.length) {
            $('#l_no_pass_error').show();
            return;
        }

        $.post('/auth.php', {username: user, password: pass, stay_logged_in: stay, format: 'json'}, function(r) {
            if (r.status) {
                var isvisitor = $.cookie('isvisitor');
                // Track the user using Google Analytics
                if( isvisitor != null && isvisitor.length > 2 ) {
                  if( isvisitor == $.cookie('myimages') ) {
                    if( pageTracker ) {
                      pageTracker._trackEvent('visitor','revisits');
                      pageTracker._trackEvent('visitor',isvisitor);
                    }
                  } else {  // Different browser?
                    if( pageTracker ) {
                      pageTracker._trackEvent('visitor',$.cookie('myimages'));
                      pageTracker._trackEvent('visitor','uniqueuser');
                    }
                    $.cookie('isvisitor', $.cookie('myimages'), {expires:365, path:'/', domain:'.imageshack.us'});
                  }
                } else {  // First login or cookie deleted
                  $.cookie('isvisitor', $.cookie('myimages'), {expires:365, path:'/', domain:'.imageshack.us'});
                  if( pageTracker ) 
                    pageTracker._trackEvent('visitor','uniqueuser');
                }
                o.dialog('close');
                document.location.replace('http://my.imageshack.us/v_images.php');
            } else {
                $('#l_auth_failed_error').show();
            }
        }, 'json');
    };

    $('#okbtn_login').bind('click', function(e) {
        do_login($(this));
        e.stopPropagation();
        e.preventDefault();
    });
    var okbtn = $('#okbtn_login').val();
    var cancelbtn = $('#cancelbtn_login').val();
    var buttons = {};
    /*
    buttons[okbtn] = function() { 
        do_login($(this));
     };
    buttons[cancelbtn] = function() { 
        // remove active status of the menu clicked
        if( $('.sfHover').length ) $('.sfHover').removeAttr("class");
        $(this).dialog('close'); 
     };
    */
    $('#login_dialog').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: 400,
        buttons: buttons,
        open:  function() {
            $('.ads').hide();
            $('.flash').hide();
            $('#l_no_user_error').hide();
            setTimeout(function() {$('#_l_user').focus()}, 100)
        },
        close: function () {
            $('.ads').show();
            $('.flash').show();
        }
    });

    $('#btnlogin,#btnlogin2,#menu_myimages').live('click', function(e) {
        if( $(this).attr("id") == "menu_myimages" && $.cookie('myimages') ) return; // In case of logged-in user
        //$('#login_dialog').show(300, function() {
          $('#login_dialog').dialog('open');
        //});
        $('.ui-widget-overlay').fadeTo(0, 0);
        $('.ui-dialog-titlebar').fadeTo(0, 0);
        $('#login_dialog').fadeTo(0, 0);
        $('.ui-widget-overlay').fadeTo(300, 0.45);
        $('.ui-dialog-titlebar').fadeTo(700, 1.0);
        $('#login_dialog').fadeTo(700, 1.0);
        e.stopPropagation();
        e.preventDefault();
    });
    
    $('#l_login,#l_password').bind('keydown', function(e) {
        if (e.which == 13) {
            do_login($('#login_dialog'));
            e.stopPropagation();
            e.preventDefault();
        }
    });

});

function set_cookie(name, value, days, domain)
{
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else 
    var expires = "";
  var cstr = name + "=" + value + expires + "; path=/";
  if (domain)
    cstr += '; domain=' + domain;
  document.cookie = cstr;
}


function focussearch(fl, def_val) {
    if (fl.value==def_val) {
        fl.value='';
        fl.style.color='black';
    }
}

function enablead() {
    if( document.getElementById('ad') )
      document.getElementById('ad').style.visibility = 'visible';
}    

function disablead() {
    if( document.getElementById('ad') )
      document.getElementById('ad').style.visibility = 'hidden';
}
      
function showBottomAd(flag) {
    if( document.getElementById('ymaddiv') ) {
      if( flag )
        document.getElementById('ymaddiv').style.visibility = 'visible';
      else
        document.getElementById('ymaddiv').style.visibility = 'hidden';
    }
}      