var soundmanager;

function busker_dialog(msg, severity) {
  if (!severity) {
    severity = 'success';
  }
    reset_dialogs({insert: false,
                   severity: severity});
    $('#ajax_alert_content').html(msg);
    $($('#ajax_alert').parents()[1]).addClass('border_'+severity);
    $('#ajax_alert').show();
    setup_dialog('#ajax_alert');
    insert_button('#ajax_alert');
    $('#ajax_alert').dialog("open");
};

function busker_alert(msg, severity) {
  if (!severity) {
    severity = 'error';
  }
  var button = '<a class="clearBtn-fixed" href="#" onclick="$(\'#messages_container\').fadeOut(); return false;"><img src="/m/img/close.gif" alt="clear"/></a>';
  $('#messages').html('<div class="alert_' + severity + '"><span class="message_text">' + msg + '</span></div>' + button);
  $($('#messages').parents()[0]).removeClass().addClass('alert_' + severity);
  $('#messages').removeClass().addClass('alert_' + severity);
  $('#messages').fadeIn();
  $('#messages_container').fadeIn();
};

function errorWidget(error) {
  return '<span class="errorInline">' + error + '</span>';
};

function debug(msg) {
  if (window.console && window.console.log) {
    console.log(msg);
  }
}

function ajaxForm(submit, form, get_data_fn, success_fn, check_fn, error_fn) {
    var next_page = gup('next');
    $(form).submit(function(e) { e.preventDefault(); $(submit).click(); return false; });
            $(submit).click(function(e) {
              e.preventDefault();
              if (check_fn && !check_fn()) {
                  return false;
              }
              $('.errorInline').remove();
              var post_data;
              if (get_data_fn) {
                post_data = get_data_fn();
              } else {
                post_data = {};
              };
              post_data.next = next_page;
              var msg;
              var action_url = $(this).attr("href");
                $.ajax({ url: action_url,
                  type: 'POST',
                  cache: false,
                  dataType: 'json',
                  data: post_data,
                  error: function(x,t,e) {
                            busker_alert(trans.ajax_error, 'error');
                                },
                         success: function(json, response) {
                            if (json.redirect) {
                              if ($('body').hasClass('playing')) {
                                    $('#overwrapper').load(json.redirect + ' .wrapper', {},
                                    function() {
                                      convert_links();
                                      bind_components();
                                    });
                                  } else {
                                    location.href=json.redirect;
                                  }
                              return false;
                            };
                            reset_dialogs(json);

                            if (json.error) {
                              if (error_fn) {
                                error_fn(json);
                              }
                            var hided;
                            var inputfield;
                            var error;
                            var fields_help;
                            if (json.error_fields && json.error_fields.count > 0) {
                                  hided = true;
                                    for(field in json.error_fields) {
                                        if ($('#' + field).length > 0) {
                                            inputfield = '#' + field;
                                        } else {
                                            inputfield = '#id_' + field;
                                        };
                                      if ($(inputfield, form).length > 0) {
                                          error = errorWidget(json.error_fields[field]);
                                          fields_help = '#id_help_' + field;
                                        if ($(fields_help,form).length > 0) {
                                            if (hided) {
                                              $('li', $(fields_help, form).parents()[0]).hide();
                                              hided = true;
                                            };
                                            $(fields_help,form).html(error);
                                            $(fields_help,form).show();
                                          } else {
                                            $(inputfield).after(error);
                                          }
                                        }
                                    }
                                }
                              msg = json.error_msg;
                            } else {
                              if (success_fn) { success_fn(json); };
                                if (json.load) {
                                    $(json.insert).load(json.load, {}, function() {
                                            $(json.insert).dialog("open");
                                            return false;
                                        });
                                };
                                if (json.msg) {
                                  msg = json.msg;
                                };
                            };
                            if (msg) {
                                $('#ajax_alert_content').html(msg);
                                $('#ajax_alert').show();
                                setup_dialog(json.insert || '#ajax_alert');
                                $('#ajax_alert').dialog("open");
                                $('#ajax_alert').css({ minHeight: '30px'});
                                $($(json.insert || '#ajax_alert').parents()[1]).addClass('border_'+json.severity);
                            }
                    return false;
                      }
                    });
                    return false; });
};

function setup_dialog(div) {
    $(div).dialog({
            autoOpen: false,
            draggable: false,
            resizable: false,
            width: 'auto',
            minWidth: 500,
            maxWidth: 700,
            height: 'auto',
            hide: 'slide',
            dialogClass: 'busker-dialog-alert',
            modal: true,
            closeOnEscape: true,
            overlay: { opacity: 0.5, background: "black" }
        });
};

function insert_button(dialog) {
/*    clear = "clear";
    $(dialog).prepend('<a id="clear_button_' + $(dialog).attr('id')  + '" class="clearBtn clearBtn-alert" href="#"><img src="/m/img/close.gif" alt="' + clear + '"/></a>');
    $('#clear_button_' + $(dialog).attr('id')).click(function(e) {
            e.preventDefault();
            $(dialog).dialog('close');
        });*/
};

function reset_dialogs(json) {
    $('#ajax_alert').removeClass();
    $($(json.insert || '#ajax_alert').parents()[1]).removeClass('border_success');
    $($(json.insert || '#ajax_alert').parents()[1]).removeClass('border_warning');
    $($(json.insert || '#ajax_alert').parents()[1]).removeClass('border_error');
    $($(json.insert || '#ajax_alert').parents()[1]).removeClass('border_info');

    if (json.error) {
        if (!json.severity) { json.severity = 'error'; };
    } else {
        if (!json.severity) { json.severity = 'success'; };
    };

    $($('#ajax_alert').children()).remove();
    $('#ajax_alert').html('<div id="ajax_alert_content"></div>');

    $('#ajax_alert_content').addClass('alert_' + json.severity);
    $(json.insert || '#ajax_alert').addClass('alert_' + json.severity);
}

/* get GET parameter value */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
};

function go_to_twitter(data) {
        var bitly_link = null;
        var title = trim(jQuery('div.title').text());
        //var author = trim(jQuery('div.author'));
        var description = "BuskerLabel: \"" + title + "\"";
        for (var r in data.results) {
            bitly_link = data.results[r]['shortUrl'];
            break;
        }
        document.location.href="http://twitter.com/home?status=" + encodeURIComponent(description + ' ' + bitly_link);
};


function trim(string) {
    var re = /\s+$|^\s+/g;
    return string.replace(re,"");
};

function unconvert_links() {
  $('body').removeClass('playing');
  $('.ajaxLink').each(function(i, el) {
                        $(el).removeClass('ajaxLink');
                        var url = $(el).attr('href');
                        if (url && url.indexOf('#') != -1) {
                          $(el).attr('href', url.slice(url.indexOf('#') + 1));
                        }
                      });
}

function convert_links(root) {
  if (!root) {
    root = 'html';
  }

  if ($('#noanchornavigation').size()) {
    return;
  }
  $(root + ' .playing a').each(function (i,el) {
                         var old = $(el).attr('href');
                         if ($(el).hasClass('button') || $(el).hasClass('button-sponsor') || $(el).hasClass("noConvert") || $(el).hasClass("ajaxLink")) {
                               return;
                         };
                         if (old && old.length > 7 && old.slice(0,7) == 'http://') {
                           return;
                         };

                         if ([$('#login_url').text(), $('#signup_url').text(), $('#need_login_url').text() ].indexOf(old) != -1) {
                           return;
                         }
                         if (old && old[0] != "#") {
                           $(el).addClass('ajaxLink');
                           if (old[0] == '?') {
                             if(jQuery.url.attr('anchor')) {
                               var current = jQuery.url.attr('anchor');
                               var newlink = '#' + current + old;
                               old = jQuery.url.setUrl(current).attr('path') + old;
                             } else {
                               var current = jQuery.url.attr('path');
                               var newlink = '#' + current + old;
                               old = jQuery.url.setUrl(current).attr('path') + old;
                             }
                           } else {
                             var newlink = '#' + old;
                           }

                           $(el).attr('href', newlink).click(function(e) {
                                                                 $('#overwrapper').load(old + ' .wrapper', {},
                                                                                        function() {
                                                                                          convert_links();
                                                                                          bind_components();
                                                                                        });
                                                               });
                         }
  });
};

function bind_events(exchange, money_flow_url, buy_coins_url, need_login_url, is_artist) {
  // general
  $('a.help.tooltip').live('click', function(e) {
                      var div = '#help_dialog_' + $(this).attr('rel');
                      e.preventDefault();
                      setup_dialog(div);
                      $(div).show();
                      setup_dialog(div);
                      insert_button(div);
                      $(div).dialog('open');
  });

  $('label').live('click', function (e) { e.preventDefault(); } );
  $('input').live('keypress', function(e) {
                        if (e.which == 13) {
                          e.preventDefault();
                          $(this).parents().filter('form').submit();
                        }});
  $('.shy').live('focus', function() {
                    if (!this.shyValue)
                      this.shyValue = $(this).val();
                    $(this).removeClass('shy');
                    if ($(this).val() == this.shyValue)
                      $(this).val('');
                  }).blur(function() {
                            if ($(this).val() == this.shyValue || $(this).val() == '')
                              $(this).addClass('shy').val(this.shyValue);
                          });

  // home.html
  $('#busker_radio > a').live('mouseover', jsddm_open);
  $('#busker_radio').live('mouseover', jsddm_canceltimer);
  $('#busker_radio').live('mouseout', jsddm_timer);

  var timeout    = 200;
  var closetimer = 0;
  var ddmenuitem = 0;

  function jsddm_open()
  {  jsddm_canceltimer();
     jsddm_close();
     $('#busker_radio_menu').css({visibility: 'visible'});
     }

  function jsddm_close()
  {  $('#busker_radio_menu').css({visibility: 'hidden'}); }

  function jsddm_timer()
  {  closetimer = window.setTimeout(jsddm_close, timeout);}

  function jsddm_canceltimer()
  {  if(closetimer)
     {  window.clearTimeout(closetimer);
        closetimer = null;}}

  $('body').live('click', jsddm_close);

  $('#busker_radio a').live('click', function(e) {
                              e.preventDefault();
                              $('#player_container').load($(this).attr('href')  + ' #player', {}, softSetupPlayListAndPlay);
                            });

  $("#more_activities").live('click', function(e) {
                                e.preventDefault();
                                if (!running) {
                                  running = true;
                                  $("#image_indicator").show();
                                  $("#last_activities").append('<div id="activities_tmp"></div>');
                                  $("#activities_tmp").load(ajax_wall_url + '?page=' + page + ' .entry_list', {}, function(data, textResponse) {
                                    var last = $("#activities_tmp ul.entry_list");
                                    $("#activities_tmp ul.entry_list").unwrap();
                                    $("#image_indicator").hide();
                                    last.hide().fadeIn('slow');
                                    page = page + 1;
                                    running = false;
                                    if (page == 10) {
                                      $("#more_activities").hide();
                                    }
                                                            });
                                }
                              });


/* faq.html */
  $(".faq").live('click', function(e)  {
                   e.preventDefault();
                   $(this).next().next().toggle();
                 });

  $(".delete_link").live('click',
                         function(event) {
                           event.preventDefault();
                           $("#delete form").attr("action", $(this).attr("href"));
                           $(".username").html($(this).attr("title"));
                           $("#delete").show();
                           $("#delete").dialog("open");
  });

  /* money coins.html */
  $("#sellbutton").live('click', function(event) {
        event.preventDefault();
        $("#selling_dialog_content").show();
        $("#selling_method_dialog").dialog("open");
    });


  $("#buybutton").live('click', function(event) {
        event.preventDefault();
        if (parseInt($("#id_buy_coins").val()) >= 5) {
            $("#payment_dialog_content").show();
            $("#payment_method_dialog").dialog("open");
        } else {
            busker_alert("You can not buy less than 5 Koins", "warning");
        }
    });

  $("#sell_form").live('submit', function(event) {
        event.preventDefault();
        $("#selling_method_dialog").dialog("open");
    });

  $("#id_sell_coins").live('keyup', function(e) { currency_update(exchange); });
  $("#id_buy_coins").live('keyup', function(e) { currency_update(exchange); });
    $("#filter").click(function(event) {
        $("#money_flow").load(money_flow_url, {
            from_date: $("#id_from_date").val(),
            to_date:   $("#id_to_date").val(),
            show:      $("#id_show").val()
                              });
    });

  $("#download").live('click', function(event) {
        event.preventDefault();
        $("#id_download").val("True");
        $("#filterform").submit();
    });

  $("#id_from_date").live('keyup', function(event) {
        if (event.which == 13) {
            $("#money_flow").load(money_flow_url, {
                from_date: $("#id_from_date").val(),
                to_date:   $("#id_to_date").val(),
                show:      $("#id_show").val()
            });
        }
    });

  $("#id_to_date").live('keyup', function(event) {
        if (event.which == 13) {
            $("#money_flow").load(money_flow_url, {
                from_date: $("#id_from_date").val(),
                to_date:   $("#id_to_date").val(),
                show:      $("#id_show").val()
            });
        }
    });

  $("#id_show").live('change', function(event) {
        $("#money_flow").load(money_flow_url, {
            from_date: $("#id_from_date").val(),
            to_date:   $("#id_to_date").val(),
            show:      $("#id_show").val()
        });
    });

  // $.datepicker.setDefaults($.datepicker.regional["it"]);

  $("#paypal_buy_coins").live('submit', function (event) {
        event.preventDefault();
        $.ajax({
            cache: false,
            url:buy_coins_url,
            data: {
                "amount_coins": $("#amount_copy").text(),
                "transaction_type": "buy"
            },
            dataType: "json",
            error: function(x,t,e) {
              busker_alert(trans.ajax_error, 'error'); },
            success: function (data, textStatus) {
                $("#id_invoice").val(data.invoice);
                $("#transaction_id").val(data.id);
                $("#id_cancel_return").val($("#id_cancel_return").val() + data.id);
                $("#paypal_buy_coins").get(0).submit();
            },
            type: "POST"
        });
    });

  $('.settle_dialog_link').live('click', function(e) {
    e.preventDefault();
    form = $(this).parents('form').get(0);
    $("#confirm_settlement_dialog").show();
    $("#settle_ok").attr('href', $(form).attr('action'));
    $("#settlement_album").html($($(form).children()[2]).val());
    $("#settlement_amount").text($($(form).children()[0]).val());
    $("#settlement_currency_amount").text($($(form).children()[1]).val());
    $("#confirm_settlement_dialog").dialog('open');
    return false;
  });

  $("#settle_cancel").live('click', function(e) {
    e.preventDefault();
    $("#confirm_settlement_dialog").dialog('close');
  });

  $(".delete_link").live('click', function(event) {
                           event.preventDefault();
                           $("#delete form").attr("action", $(this).attr("href"));
                           $(".album_name").html($(this).attr("title"));
                           $("#delete").show();
                           $("#delete").dialog("open");
  });

  $(".download_link").live('click', open_download);

$('#require_code').live('click', function(e) {
                          e.preventDefault();
                          $('#require_dialog').show();
                          $('#require_dialog').dialog("open");
                        });

  $(".to_eval_link").live('click', function(event) {
            event.preventDefault();
            $("#to_evaluating form").attr("action", $(this).attr("href"));
            $("#album_name").html($(this).attr("title"));
            $("#to_evaluating").show();
            $("#to_evaluating").dialog("open");
        });

  $("#visibility").live('click', function(e) {
                          $("#no_amount").attr('checked', !("#no_amount").attr('checked'));
                          $("#no_amount").toggle();
                        });

  if (is_artist) {
    $(".jqGiveKoin").live('click', function(event) { event.preventDefault(); });
  } else {
    /* on click we check precondition before opening the dialog */
    var sponsor_url;
    $(".jqGiveKoin").live('click', function(event) {
                            event.preventDefault();
                            sponsor_url = $(this).attr("href");
                            $.ajax({ url: sponsor_url,
                            type: 'GET',
                            cache: false,
                            dataType: 'json',
                            error: function(x,t,e) { busker_alert(trans.ajax_error, 'error'); },
                            success: function(json, response) {
                              var msg;
                              if (json.error) {
                                reset_dialogs(json);
                                msg = json.error_msg;
                                $('#ajax_alert_content').html(msg);
                                $('#ajax_alert').show();
                                setup_dialog(json.insert || '#ajax_alert');
                                $('#ajax_alert').dialog("open");
                                $($(json.insert || '#ajax_alert').parents()[1]).addClass('border_'+json.severity);
                                return true;
                              } else {
                                if (json.redirect) {
                                  if ($('body').hasClass('playing')) {
                                    $('#overwrapper').load(json.redirect + ' .wrapper', {},
                                    function() {
                                      convert_links();
                                      bind_components();
                                        });
                                  } else {
                                    location.href=json.redirect;
                                    return true;
                                  };
                                };
                                if (json.buy) {
                                  $("#id_buy_coins_option").val("1");
                                  $("#buy_coins_option").show();
                                  $("#sponsor").dialog({height:420});
                                }
                                $("#sponsor_dialog_choice1").text(''+json.choices[0]);
                                $("#sponsor_dialog_choice2").text(''+json.choices[1]);
                                $("#sponsor_dialog_choice3").text(''+json.choices[2]);
                                $("#sponsor_dialog_choice4").text(''+json.choices[3]);
                                $("#amount_coins1").val(''+json.choices[0]);
                                $("#amount_coins2").val(''+json.choices[1]);
                                $("#amount_coins3").val(''+json.choices[2]);
                                $("#amount_coins4").val(''+json.choices[3]);
                                $("#sponsor #album_name").html($(this).attr("title"));
                                $("#sponsor").show();
                                $("#no_amount").attr('checked', true);
                                $("#no_amount").show();
                                $("#visibility").attr('checked', true);
                                $("#sponsor").dialog("open");
                                return true;
                              }}});
        });
    }

  $('#sponsor_submit').live('click', function(e) {
                            e.preventDefault();
                            $.ajax({ url: sponsor_url,
                            type: 'POST',
                            cache: false,
                            dataType: 'json',
                            data: { amount_coins: $("input[name=amount_coins]:checked").val(),
                            buy_amount_coins: $("input[name=buy_amount_coins]:checked").val(),
                            buy_coins_option: $("#id_buy_coins_option").val(),
                            visibility: $("#visibility").attr('checked'),
                            no_amount: !$("#no_amount").attr('checked')},
                            error: function(x,t,e) {
                              busker_alert(trans.ajax_error, 'error');},
                              success: function(json, response) {
                                $("#sponsor").dialog("close");
                                if (json.error) {
                                  busker_alert(json.error_msg, 'error');
                                } else {
                                  if ($('body').hasClass('playing')) {
                                    $('#overwrapper').load(json.redirect + ' .wrapper', {},
                                    function() {
                                      convert_links();
                                      bind_components();
                                    });
                                  } else {
                                    location.href=json.redirect;
                                  };
                                };
                              }});
                            return false;
                          });
  // album.html

  $("#withdraw_link").live('click', function(event) {
                              event.preventDefault();
                              $("#withdraw").dialog("open");
                            });

  $('#withdraw-submit-link').live('click', function (e) {
        e.preventDefault();
        $('#withdraw_form').get(0).submit();
      });

  $("#comment_link").live('click', function(event) {
                            event.preventDefault();
                            $("#comment_dialog").dialog("open");
                          });

  jQuery('.share_on_twitter').live('click', function(e) {
                                     e.preventDefault();
                                     url = jQuery(this).attr('href');
                                     BitlyClient.shorten(url, 'go_to_twitter');
                                   });

  $('#fb_exist_show').live('click', function(e) {
                              e.preventDefault();
                              $('#link_existing').show('slide');
                            });
};

function currency_update(exchange) {
  var buy = exchange * parseInt($("#id_buy_coins").val());
  if (!isNaN(buy) && buy > 0) {
    var amount = $("#id_buy_coins").val();
    var price = buy + ""; /* convert to string */
    $("#buy_currency").text(buy);
    $("#amount_copy").text(amount);
    $("#price_currency_copy").val(buy);
    $("#price_copy").text(buy);
    $("#item_name").val("A stock of " + amount + " Busker Koins");
  };

  var sell = exchange * parseInt($("#id_sell_coins").val());

  if (!isNaN(sell) && sell > 0) {
    var price = sell + "";
    $("#sell_currency").text(price);
    $("#id_amount_coins_sell_copy").val($("#id_sell_coins").val());
    $("#amount_sell_copy").text($("#id_sell_coins").val());
    $("#price_sell").text(price);
  };
};

function open_download(event) {
  event.preventDefault();
  var dialog = $(".download_" + $(this).attr('rel') + ":last");
  dialog.show();
  dialog.dialog('open');
};

function bind_components() {
  var avatar_change_url = $('#avatar_change_url').text();
  var ajax_avatar_url = $('#ajax_avatar_url').text();
  var ajax_wall_url = $('#ajax_wall_url').text();
  var profile_country_autocomplete_url = $('#profile_country_autocomplete_url').text();
  var profile_town_autocomplete_url = $('#profile_town_autocomplete_url').text();

  // general
  $('input').attr('autocomplete', 'off');

 /* require_code_dialog.html */
  $('#require_dialog').dialog({
                                autoOpen: false,
                                draggable: false,
                                width: 'auto',
                                open: function() {
                                  $('#require_dialog').css({width: '100%'});
                                  $($('#require_dialog').parents()[1]).css({width: 'auto'});
                                },
                                resizable: false,
                                dialogClass: 'busker-dialog',
                                modal: true,
                                overlay: { opacity: 0.3, background: "black" }});

  /* account/base.html */
  $('#tabs').tabs().show();
  setup_dialog('#delete');

    ajaxForm('#btn_change_password', '#cpform',
           function() { return {
                          oldpassword: $('#id_oldpassword').val(),
                          password1: $('#id_password1').val(),
                          password2: $('#id_password2').val() };
                      });

  ajaxForm('#btn_update_identity', '#idform', function() {
             return {
               first: $('#id_first').val(),
               middle: $('#id_middle').val(),
               last: $('#id_last').val(),
               address: $('#id_address').val(),
               birthday: $('#id_birthday').val(),
               city: $('#id_city').val(),
               state: $('#id_state').val(),
               zipcode: $('#id_zipcode').val(),
               country: $('#id_country').val()
             };
  });
  ajaxForm('#btn_update_payment', '#payform', function () {
             return {
               paypal_email: $('#id_paypal_email').val(),
               email: $('#id_email').val()
             };
  });
  $("#id_birthday").datepicker({
                                 yearRange: '1909:2009',
                                 changeMonth: true,
                                 changeYear: true,
                                 dateFormat: 'dd/mm/yy',
                                 firstDay: 1 });

  /* password_reset.html */
  ajaxForm('#reset_pwd_btn', '#password_reset_form', function() { return { email: $('#id_email').val() }; });

  /* faq.html */
    $(".faq").next().next().hide();

  /* money/coins.html */
  if ($("#money_flow").size()) {
    $("#money_flow").load($('#money_flow_url').text());
    $("#id_from_date").datepicker();
    $("#id_to_date").datepicker();
    currency_update(parseFloat($('#sell_rate').text()));
  }

  $("#payment_method_dialog").dialog({
            autoOpen: false,
            draggable: false,
            dialogClass: 'busker-dialog',
            resizable: false,
            width: 'auto',
            open: function() {
               $('#payment_method_dialog').css({width: '100%'});
               $($('#payment_method_dialog').parents()[1]).css({width: 'auto'});
            },
            modal: true,
            overlay: { opacity: 0.5, background: "black" }
  });

  $("#selling_method_dialog").dialog({
            autoOpen: false,
            draggable: false,
            resizable: false,
            width: 'auto',
            open: function() {
               $('#selling_method_dialog').css({width: 'auto'});
               $($('#selling_method_dialog').parents()[1]).css({width: 'auto'});
            },
            dialogClass: 'busker-dialog',
            modal: true,
            overlay: { opacity: 0.5, background: "black" }
        });

  // money/coins_artist.html
  insert_button('#confirm_settlement_dialog');
  setup_dialog("#confirm_settlement_dialog");
  ajaxForm('#settle_ok', '#settleform', function() { return {};} );

  // contact.html
  ajaxForm('#contact_btn', '#contact', function() { return  {  email: $('#id_email').val(),  feedback: $('#id_feedback').val() }; });

  // delete_dialog.html
  insert_button('#delete');
  setup_dialog('#delete');

  // download dialog
  $(".download_dialog").dialog({
            autoOpen: false,
            draggable: false,
            width: 'auto',
            resizable: false,
            open: function(event, ui) {
                $(ui).css({width: '100%'});
            },
            dialogClass: 'busker-dialog',
            modal: true,
            overlay: { opacity: 0.25, background: "black" }
        });

  // move_to evaluating
  $("#to_evaluating").dialog({
    autoOpen: false,
    draggable: false,
    height: 100,
    dialogClass: 'busker-dialog',
    modal: true,
    overlay: { opacity: 0.5, background: "black" }
  });

  // sponsor button
  var sponsor_url = "";
  $("#sponsor").dialog({
    autoOpen: false,
    draggable: false,
    resizable: false,
    width: 'auto',
    open: function() {
      $('#sponsor').css({width: '100%'});
      $($('#sponsor').parents()[1]).css({width: 'auto'});
    },
    dialogClass: 'busker-dialog',
    modal: true,
    overlay: { opacity: 0.3, background: "black" }
  });

  // album.html
  ajaxForm('#add_fav_submit', '#add_fav');
  ajaxForm('#rem_fav_submit', '#rem_fav');

  $("#withdraw").dialog({
    autoOpen: false,
    draggable: false,
    width: 600,
    height: 400,
    modal: true,
    overlay: { opacity: 0.5, background: "black" }
      });
  setup_dialog("#comment_dialog");

  if ($('#change_avatar_btn').size()) {
    var profilePicUp = new AjaxUpload('#change_avatar_btn',
            { action: avatar_change_url,
                name: 'avatar',
                autosubmit: true,
                onSubmit: function(file, extension) {
                    $($('#image_indicator').siblings()[0]).hide();
                    $('#image_indicator').show();
                }, /* return false if we don't like */
                onComplete: function(file, response) {
                    $('#image_indicator').hide();
                    $($('#image_indicator').siblings()[0]).show();
                    $('#profile_avatar').load(ajax_avatar_url);
                }});
  };

  // profiles/edit.html
  $("#id_country").autocomplete(profile_country_autocomplete_url, {
                                  formatItem: function(data, i, n, value) {
                                    return value;
                                  },
                                  formatResult: function(data, value) {
                                    return value;
                                  },
                                  highlight: false // TODO: improve highlighting to only affect username.
                                });
  $("#id_country").result(function() {
                            $("#town").val("");
                            $("#town").focus();
                          });
  $("#town").autocomplete(profile_town_autocomplete_url, {
    extraParams: {
      country: function() { return $("#id_country").val(); }
    },
    formatItem: function(data, i, n, value) {
      return value;
    },
    formatResult: function(data, value) {
      return value;
    },
    // TODO: improve highlighting to only affect username.
    highlight: false
      });

      ajaxForm('#btn_edit_profile', '#edit_profile_form',
               function() { return {
                              artist_name: $('#id_artist_name').val(),
                              about: $('#id_about').val(),
                              website: $('#id_website').val(),
                              myspace: $('#id_myspace').val(),
                              facebook: $('#id_facebook').val(),
                              youtube: $('#id_youtube').val(),
                              country: $('#id_country').val(),
                              town: $('#town').val()
                            };});
  // signup.html
  ajaxForm('#signup_link', '#signup_form',
  function () {
    var is_artist;
    if ($('#is_artist').size()) {
      is_artist = "true";
    } else {
      if ($('#is_fan').size()) {
        is_artist = "false";
      } else {
        is_artist = $('#id_is_artist').attr('checked');
      }
    }

    return {
      fbregister: $('#fbregister'),
      username: $('#id_username', '#signup_form').val(),
      password1: $('#id_password1').val(),
      password2: $('#id_password2').val(),
      email: $('#id_email').val(),
      confirmation_key: $('#id_confirmation_key').val(),
      signup_code: $('#id_signup_code').val(),
      is_artist: is_artist,
      artist_name: $('#id_artist_name').val(),
      terms: $('#id_terms').attr('checked')
    };
  }, null, null,
  function () { });

  if (!$('#is_artist').size()) {
    /* hide artist fields */
    $('#fieldWrapper_artist_name').hide();
    $('#fieldWrapper_artist_name2').hide();

    /* toggle artist fields */
    $('#id_is_artist').change(function() {
                                if($('#id_is_artist:checked').val()) {
                                  $('#fieldWrapper_artist_name').show();
                                  $('#fieldWrapper_artist_name2').show();
                                } else {
                                  $('#fieldWrapper_artist_name').hide();
                                  $('#fieldWrapper_artist_name2').hide();
                                };
                              });
  }

  ajaxForm("#invite_link", '#invite_form', function() {
             var role =  $('.invite_role:checked').val();
             return {
               action: 'apply',
               email: $('#id_email_applicant').val(),
               role: role}; });

  ajaxForm("#login_link", '#login_form', function() {
             return {
               action: 'login',
               password: $('#id_password').val(),
               username: $('#id_username').val(),
               remember_me: $('#id_remember_me').attr('checked')
             };
        });
  ajaxForm("#fb_login_link", '#login_form', function() {
             return {
             action: 'login',
             fblogin: $('#fb-uid').text(),
             password: $('#id_password').val(),
             username: $('#id_username').val(),
             remember_me: $('#id_remember_me').attr('checked')
             };
        });
  ajaxForm('#fbsignup_link', '#fbsignup_form',
  function () {
    var is_artist;
    if ($('#is_artist').size()) {
      is_artist = "true";
    } else {
      if ($('#is_fan').size()) {
        is_artist = "false";
      } else {
        is_artist = $('#id_is_artist').attr('checked');
      }
    }

    return {
      fbregister: $('#fbregister'),
      username: $('#id_username', '#signup_form').val(),
      password1: $('#id_password1').val(),
      password2: $('#id_password2').val(),
      email: $('#id_email').val(),
      confirmation_key: $('#id_confirmation_key').val(),
      signup_code: $('#id_signup_code').val(),
      is_artist: is_artist,
      artist_name: $('#id_artist_name').val(),
      terms: $('#id_terms').attr('checked')
    };
  }, null, null,
  function () { });

  // home.html
  if ($('#last_activities_container').size()) {
    $("#last_activities").load(ajax_wall_url + ' .entry_list', {}, function(data, textResponse) {$("#image_indicator").hide(); $("#last_activities ul").hide().fadeIn('slow');});
  }

  change_play_button_state();
}

// it refers to home page activities
var running = false;
var page = 2;


