pretty_numbers = function(v) {
  v = String(v);
  var ps = v.split('.');
  var whole = ps[0];
  var sub = ps[1] ? '.'+ ps[1] : '';
  var r = /(\d+)(\d{3})/;
  while (r.test(whole)) {
      whole = whole.replace(r, '$1' + ',' + '$2');
  }
  v = whole + sub;
  if(v.charAt(0) == '-'){
      return '-' + v.substr(1);
  }
  if(v == 'null'){
    v = 0;
  }
  return v;
};

function cpaTrack(type){
    var trkDiv=document.getElementById('trackers_div');
    var baseurl='http://headliner.fm/exchange/trackers/';
    var trkstr = "";
    trkstr += "<iframe width=0 height=0";
    trkstr += " border=0 src='"+baseurl+type+".html'><\/iframe>";
    trkDiv.innerHTML=trkstr;
    if(type=="signup"){
        setTimeout('send_to_exchange()',2000);
    }
}


function send_to_exchange() {
window.location = 'http://headliner.fm/exchange/';
}


$(document).ready(function(){
  // ===========================
  // = SET FOCUS TO NAVIGATION =
  // ===========================
  var sPath = window.location.pathname;
  var sPage = sPath.substring(sPath.lastIndexOf('/') + 1, sPath.length - 4);
  if(sPage == "/"){
    $('#index').addClass('selected');
  }else{
    $('#' + sPage).addClass('selected');
  }

  // =================
  // = QUOTE ROTATOR =
  // =================
  $("#quotes").quoterotator({
		speed : 5000,
		json : "js/quoterotator_quotes.js?r=1357"
	});
	
	// ==============
	// = TOTAL FANS =
	// ==============
  $.ajax({
    type: "GET", url: '/exchange/global_static/total_fans.json', data: '', dataType: "json",
    success: function(data) { $('#total_fans').html(pretty_numbers(data.total_fans)); }
  });

	// ==============
	// = TICKER =
	// ==============  
  $.ajax({
    type: "GET", url: '/exchange/global_static/total_fans.json', data: '', dataType: "json",
    success: function(data) {

      var tickerdata = pretty_numbers(data.total_fans);
      var tickersplit = tickerdata.split("");
      var tickerhtml = '';
      for ( var i=0; i<tickersplit.length; i++ ){
        if (tickersplit[i] == ",") {
        	tickerhtml += "<div class=\"comma\">" + tickersplit[i] + "</div>";
        } else {
          tickerhtml += "<div class=\"digit\">" + tickersplit[i] + "</div>";
        }
      }
      $('#ticker').html(tickerhtml);
    }
  });

  // =============
  // = FORM CRAP =
  // =============
  var texttypes = 'input[type="text"], textarea, input[type="password"]';
  $(texttypes).addClass("idleField");

  //input box focused
  $(texttypes).focus(function() {
    $(this).removeClass("idleField").addClass("focusField");
    if (this.value == this.defaultValue){
      this.value = '';
    }
  });

  //input box unfocused
  $(texttypes).blur(function() {
    $(this).removeClass("focusField").addClass("idleField");
    if ($.trim(this.value) == ''){
      this.value = (this.defaultValue ? this.defaultValue : '');
    }
  });

  $('#myspace_results').hide();
  $('#email_results').hide();
  $('#signup_results').hide();

  myspace_submitted = false;
  white = "";

  //SUBMIT MYSPACE FAN FORM
  //START SUBMITTING MYSPACE FRIEND COUNT
  $("#submit_myspace").click(function() {
    var input_myspace_val = $("input#myspace").val();
    var script_name = 'http://headliner.fm/band_data/myspace/url/';
    var script_params = 'url=http://www.myspace.com/'+input_myspace_val;

    /*
     * A LOCAL (DEVELOPMENT) END POINT TO GET MYSPACE FAN COUNT.
     * uncomment to see what a successful message would look like.
    */
    // script_name = 'myspace_fans.php?';
    // script_params = 'url='+input_myspace_val;

    if(input_myspace_val != '' && input_myspace_val != 'MySpace ID'){
      $.ajax({
        type: "GET", url: script_name, data: script_params, dataType: "json",
        success: function(data) {
          var success = data.success;
          var bb = data.fan_count;

          if(success && bb>1) {
            $('#myspace_results').html("<h2 style='margin:0px 0px 10px 0px'>SUCCESS!</h2>")
            .append("Your band is worth <span class='text20orange'>" + pretty_numbers(bb) + "</span> Band Bucks!<br/>")
            .append("You can reach <span class='text20blue'>" + pretty_numbers(bb) + "</span> new fans!<br/><br/>")
            .append("<h2>Sign up for Headliner.fm Beta below!</h2>")
            .show(500, function(){
              $('#email_section').animate({backgroundColor:"#0677B1"},500);
              $('#beta_signup').css("color","#FFFFFF");
              $('#artist_question').css("color","#FFFFFF");
              $("input#email").focus();
              white = 'color: white';
            });
          } else {
            $('#myspace_results').html("<div id='wrapper'><div class='left'><img src='images/icon_yield.gif'></div><div class='left errorbox'><span class='bold'>Not Found</span><p>MySpace ID was not found. Try Again!</p></div><div class='clear'></div></div>")
            .show(500);
          }
        },
        error: function() {
          $('#myspace_results').html("<div id='wrapper'><div class='left'><img src='images/icon_yield.gif'></div><div class='left errorbox'><span class='bold'>Server Error!</span><p>Please try again later.</p></div><div class='clear'></div></div>")
          .show(500);
        }
      });
    } else {
      $('#myspace_results').html("<div id='wrapper'><div class='left'><img src='images/icon_yield.gif'></div><div class='left errorbox'><span class='bold'>Error!</span><p>Please try enter your MySpace ID!</p></div><div class='clear'></div></div>")
      .show(500);
      $("input#myspace").focus();
    }
    return false;
  });

  //SUBMITTING EMAIL
  $("#submit_email").click(function() {
    var email = $("input#email").val();
    if(email != '' && email != 'Email Address'){
      $.ajax({
        type: "GET", url: "includes/email.php", data: "email="+email, dataType: "json",
        success: function(data, textStatus) {
          var res = data.success;
          if(res == true){
            $('#email_results').html([
              "<h2 style='"+white+"'>Thank you!</h2>",
              "<p style='"+white+"'>Thank you for your interest in headliner.fm's Beta program!<br/>",
              "We will be contacting you in a bit. :)</p>"
              ].join('')).show(500);
          }else{
            $('#email_results')
            .html("<div id='wrapper'><div class='left errorbox'><span class='bold' style='"+white+"'>Error!</span><p style='"+white+"'>Please enter a valid email address.</p></div><div class='clear'></div></div>")
            .show(500);
          }
        }
      });
    } else {
      $('#email_results').html("")
      .append("<div id='wrapper'><div class='left errorbox'><span class='bold' style='"+white+"'>Error!</span><p style='"+white+"'>Please enter a valid email address.</p></div><div class='clear'></div></div>")
      .show(500);
    }
  });
  //END SUBMITTING EMAIL

  //START INVITED?
  $("#invited_by").click(function(){
    $("#inviter_div").show(500);
  });
  //END INVITED?

  //START GENRE DROPDOWN
  $.getJSON('/exchange/music_genres.json', function(data){
    var options_genres = '<option value="false" disabled>Please Select a Genre...</option>';
    $.each(data, function(i,d){
      if(d.name !== 'All' && d.name !== 'Other'){
        options_genres += '<option value="' + d.id + '">' + d.name + '<\/option>';
      }
    });
    $("#music_genres").html(options_genres);
  });
  //END GENRE DROPDOWN

  //START SUBMITTING SIGNUP
  $("#submit_signup").click(function(){
    var artist_name = $("input#artist_name").val();
    var email = $("input#email").val();
    var zipcode = $("input#zipcode").val();
    var pwd = $("input#pwd").val();
    var pwd_conf = $("input#pwd_conf").val();
    var tos = $("input#tos").val();
    var tsid = $("input#tsid").val();
    var newsletter = $("input#newsletter").val();
    
    $("#signup_form").validate({
      rules: {
        artist_name   : {required:true},
        music_genres  : {required:true, digits:true},
        email         : {required:true, email:true},
        zipcode       : {required:true, minlength:3},
        pwd           : {required:true, minlength:5},
        pwd_conf      : {required:true, minlength:5, equalTo: "#pwd"}
      },
      messages: {
         artist_name    : "<b>Artist Name</b> is required.<br/>",
         email          : "<b>Valid Email</b> is required.<br/>",
         music_genres   : "<b>Genre</b> is required.<br/>",
         zipcode        : "<b>Valid Zip Code</b> is required.<br/>",
         pwd            : "<b>Password</b> must be at least 5 Characters.<br/>",
         pwd_conf       : "<b>Passwords</b> do not match.<br/>"
      }, 
      errorLabelContainer: $("#signup_results"),
      submitHandler: function(form) {
        var data = {
          "s_name"          : $("input#artist_name").val(),
          "s_login"         : $("input#email").val(),
          "s_password_f"    : $("input#pwd").val(),
          "s_password_r"    : $("input#pwd_conf").val(),
          "zipcode"         : $("input#zipcode").val(),
          "tsid"            : $("input#tsid").val(),
          "s_inviter"       : $("input#inviter_email").val(),
          "utype"           : "band",
          "music_genre_id"  : $("select#music_genres").val(),
          "optin_headliner" : $("input#optin_headliner").is(':checked'),
          "optin_others"    : $("input#optin_others").is(':checked')
        };
        $.ajax({
          type: "POST", url: "/exchange/users", data: data, dataType: "json",
          beforeSend: function() {
            $('#loader').css("display","block");
          },
          success: function(data) {
            var success = data.success;
            $('#loader').css("display","none");

            if(success) {
              var email = $("input#email").val();
              var email_append = "";
              //send email to corresponding email list, if need be
              if(tsid.indexOf('contest_blg') != -1 && newsletter == 'true') {
                email_append="<img height='0' width='0' src='includes/sonic_email.php?email="+email+"'>";
               }

              $('#signup_results')
              .css("background-color","#afe4ff")
              .css("border","1px solid #018cd2")
              .html("<span class='bold'>Success!</span>")
              .append(" <a href='http://headliner.fm/exchange/' target='_blank'>Login</a> to get started!")
              .append(email_append)
              .show(500);
              cpaTrack('signup');

              //reset values
              $("input#artist_name").val('');
              $("input#email").val('');
              $("input#pwd").val('');
              $("input#pwd_conf").val('');
              $("input#zipcode").val('');
            } else {
              $('#signup_results')
              .css("background-color","#ffebe8")
              .css("border","1px solid #dd3c10")
              .html("<span class='bold'>Email address already exists!</span>")
              .show(500);
              $("input#email").focus();
            }
          },
          error: function() {
            $('#loader').css("display","none");
            $('#signup_results')
            .css("background-color","#ffebe8")
            .css("border","1px solid #dd3c10")
            .html("<span class='bold'>Server Error!</span><br/>Please try again later!<br>")
            .show(500);
          }
        });//END .ajax
      }//END submitHandler
    });//END .validate
  });//END .click
  

  //START features page content
  $("#div_1").click(function () {
    $('#div_content').html([
    '<h1>Send out your band’s promotion message to millions of new fans.</h1>',
    '<h3><br>Got a show coming up? With Headliner you can let millions of people know about it. Its easy, just write a short message and send it out to a few bands. They will pass it on to their fans in the form of a status update through social media, allowing you to reach far more fans than ever before.</h3>'
    ].join(""));
    $('#div_1').removeClass('unselected');
    $('#div_1').addClass('selected');
    $('#div_2, #div_3, #div_4, #div_5').addClass('unselected');
  });
  
  $("#div_2").click(function () {
    $('#div_content').html([
      '<h1>Earn Band-Buck for all your existing fans on Facebook, Twitter and MySpace.</h1>',
      '<h3><br>Headliner gives you value for the fans you already have. Headliner gives you Band Bucks for each fan you have on Facebook, Myspace and Twitter when you connect your pages to the system. You can use these Band Bucks to run promotions without ever spending any money. Headliner also gives you Band Bucks when you accept promotions for other cool bands you like.</h3>'
    ].join(""));
    $('#div_2').removeClass('unselected');
    $('#div_2').addClass('selected');
    $('#div_1, #div_3, #div_4, #div_5').addClass('unselected');
  });
  
  $("#div_3").click(function () {
    $('#div_content').html([
      '<h1>Hyper-target fans on Facebook, Twitter and MySpace.</h1>',
      '<h3><br>When you place an ad on a website or on Facebook and MySpace you end up advertising to many people who are uninterested in your music. On Headliner you can easily target just the fans you need. Your message goes to fans in the form of a recommendation from a band they already like, so find a bunch of bands in your genre and ask them to pass your message on. They are already music fans who enjoy music similar to yours these fans are much more respective to checking out your music.</h3>'
    ].join(""));
    $('#div_3').removeClass('unselected');
    $('#div_3').addClass('selected');
    $('#div_1, #div_2, #div_4, #div_5').addClass('unselected');
  });

  $("#div_4").click(function () {
    $('#div_content').html([
      '<h1>Watch your promotions react with real-time analytics.</h1>',
      '<h3><br>Headliner gives you detailed metrics so you know exactly how many people saw your message and clicked on your link. A promotion on Headliner isn\'t a shot in the dark but rather a highly targeted system with measurable results.</h3>'
    ].join(""));
    $('#div_4').removeClass('unselected');
    $('#div_4').addClass('selected');
    $('#div_1, #div_2, #div_3, #div_5').addClass('unselected');
  });
  
  $("#div_5").click(function () {
    $('#div_content').html([
      '<h1>100% authentic and band endorsed.</h1>',
      '<h3><br>Every message sent out by Headliner is artist approved. Before a message goes out on Twitter, Myspace or Facebook it has to be accepted, so every message is authentic and band endorsed.</h3>'
    ].join(""));
    $('#div_5').removeClass('unselected');
    $('#div_5').addClass('selected');
    $('#div_1, #div_2, #div_3, #div_4').addClass('unselected');
  });//END features page content



  //START artist guide page content
  $("#ag_div_1").click(function () {
    $('#div_content').html([
    '<h1>About headliner.fm</h1>',
    '<h5>Every day more bands are joining Headliner and getting their music heard. With Headliner, fans are only a click away and targeting the right fans is easy. From platinum selling artists on major labels to DIY musicians who haven\'t played outside of their own apartments, thousands of bands and artists are discovering the value of Headliner.</h5>',
    '<p class="text14gray">When Anarbor was nominated for a MTVU Freshman band of the week spot, they turned to Headliner to put them over the top. When Rob Thomas wanted to get the word out about his latest project, he used Headliner to get fans buzzing about it. Bands of all sizes have found success with Headliner and have used it to get their music into the iPods of music listeners all over the world.</p>',
    '<p class="text16gray3 bold">What Can Headliner Do For Bands and Artists?</p>',
    '<p class="text14gray">Headliner is a promotional platform that helps artists reach new fans. Share a message with thousands of music fans, get direct traffic to your Twitter, Facebook or Myspace account and get more people to download your new single on iTunes-- all from one easy to use dashboard. Headliner will supply detailed metrics, so you know exactly how effective your promotion has been.</p>',
    '<p class="text16gray3 bold">Who Is It For?</p>',
    '<p class="text14gray">Headliner is a tool for musicians, bands, labels, managers, concert promoters and bookers. Bands of all sizes use Headliner. Whether you have one fan or one million fans, Headliner can help you find more.</p>',
    '<p class="text16gray3 bold">Why Headliner?</p>',
    '<p class="text14gray">Headliner gets your message out to music fans.  Headliner\'s service is unique; many sites offer bands opportunities to upload their music and slowly gain fans, but only Headliner offers users the ability to reach the fans of thousands of other bands in real-time</p>'
    ].join(""));
    $('#ag_div_1 div').removeClass('unselected');
    $('#ag_div_1 div').addClass('selected');
    $('#ag_div_2 div, #ag_div_3 div, #ag_div_4 div, #ag_div_5 div').addClass('unselected');
  });
  
  $("#ag_div_2").click(function () {
    $('#div_content').html([
      '<h1>Getting Started</h1>',
      '<h5>So you are excited about Headliner. Now what?</h5>',
      '<p class="text16gray3 bold">Sign up</p>',
      '<p class="text14gray">Join the exchange.  If you are a band or an artist, select "Band/Artist". If you are a label, manager or represent multiple artists select "Label/Management Group".  Headliner will send notifications to the email address you provide when other artists have requested promotions with your band.<br/><br/>Note: If you are a band or artist based outside of the United States you will have to enter a postal code of 00000.</p>',
      '<img src="/images/ag_snicons.jpg" style="float:right">',
      '<p class="text16gray3 bold">Enter the exchange</p>',
      '<p class="text14gray">Link your Twitter, Facebook and Myspace accounts into Headliner. Click the "Social Networks" tab in the Headliner Exchange and click on the corresponding logos to authorize your band\'s social networks.<br/><br/> Note: It is only possible to link Facebook Fan Pages to Headliner. Personal Facebook pages simply will not connect to the system at this time. For more information on creating a Facebook Fan Page, <a href="http://www.facebook.com/pages/create.php">go here.</a></p>',
      '<img src="/images/ag_bandbucks.jpg" style="float:right">',
      '<p class="text16gray3 bold">Why link your accounts?</p>',
      '<p class="text14gray">When you link Twitter, Facebook or Myspace account to Headliner, you will receive 1x Band Bucks for every fan, friend or follower you have on that account. Use your Band Bucks to reach new fans on Headliner.  <br/><br/> Note: In order to use Headliner, you MUST link at least one social networking account to the system.</p>',
      '<p class="text14gray">After a band accepts your message on Headliner, it goes out to their fans through their Twitter, Facebook and Myspace accounts in the form of a status update.</p>',
      '<img src="/images/ag_accept.jpg" style="float:right">',
      '<p class="text16gray3 bold">What are Band Bucks for?</p>',
      '<p class="text14gray">Band Bucks incentivize artists to accept promotions. When other bands accept your promotions they will receive Band Bucks. You can earn more Band Bucks by accepting promotion requests from other artists.</p>'
    ].join(""));
    $('#ag_div_2 div').removeClass('unselected');
    $('#ag_div_2 div').addClass('selected');
    $('#ag_div_1 div, #ag_div_3 div, #ag_div_4 div, #ag_div_5 div').addClass('unselected');
  });
  
  $("#ag_div_3").click(function () {
    $('#div_content').html([
      '<h1>Create a Promotion</h1>',
      '<h5>Creating a promotion on Headliner lets bands connect with thousands of new fans. With Headliner you send your promotion request out to other artists. After they approve it, your message goes out to their fans in the form of a status update on their Twitter, Facebook and Myspace. Sending a promotion may seem confusing at first, but it is actually extremely simple.  Just follow the rules on this page and find out for yourself.</h5>',
      '<p class="text16gray3 bold">The Basics</p>',
      '<p class="text14gray">There are several things to keep in mind when you create a promotion on Headliner. Run your promotion a few days in advance, so other artists will have time to see and accept the request before it expires. Send requests to smaller bands.  Fans of lesser known artists are more engaged than fans of larger artists, which means your promotion message will perform better.</p>',
      '<ul>',
      '<li><p class="text14gray">Promote with artists whose fans who will enjoy your music.</p></li>',
      '<li><p class="text14gray">Use Headliner’s URL shortener so we can track the campaign for you.</p></li>',
      '<li><p class="text14gray">It is important you create messages that are positive, but not disingenuous. So, while a message like "Check out this great band" is a good message a message like "Check out our favorite band" is not.</p></li>',
      '</ul>',
      '<p class="text16gray3 bold">Promote an upcoming show</p>',
      '<img src="/images/ag_tickets.jpg" style="float:left;">',
      '<p class="text14gray">A few days before your show create a promotion message telling people the day and time.  Schedule the message to go out on the day of or before the show.',
      '<blockquote class="text14gray"><span class="ital">Example:</span> "Hey check out (Your Band’s Name) show tonight at the Bowery Ballroom. Snag a Ticket here: ( link to where people can get tickets)"</blockquote></p>',
      '<p class="text16gray3 bold">Reach new fans</p>',
      '<img src="/images/ag_fans.jpg" style="float:left;">',
      '<p class="text14gray">Create a promotion message asking people to follow, or become a fan of your band.<br/>',
      '<blockquote class="text14gray"><span class="ital">Example:</span> "Check out ( Your Band’s Name ) on Twitter. Post a link to your Twitter.</blockquote></p>',
      '<p class="text16gray3 bold">Sell your music</p>',
      '<img src="/images/ag_music.jpg" style="float:left;">',
      '<p class="text14gray">Create a promotion message and point people to where they can buy your music online.<br/>',
      '<blockquote class="text14gray"><span class="ital">Example:</span> "Check out a new song by ( Your Band’s Name )." Post a link to your iTunes.</blockquote></p>',
      '<p class="text16gray3 bold">Sell your merch</p>',
      '<img src="/images/ag_merch.jpg" style="float:left;">',
      '<p class="text14gray">Create a promotion message about your merch.</p>',
      '<blockquote class="text14gray"><span class="ital">Example:</span> "Check out this new cool tee from ( Your Band’s Name )"',
      'Post a link to where people can buy your merch.<br/><br/></blockquote></p>',
      '<p class="text16gray3 bold">Create a contest</p>',
      '<img src="/images/ag_prize.jpg" style="float:left;">',
      '<p class="text14gray">Create a promotion message around a contest for your band.<br/>',
      '<blockquote class="text14gray"><span class="ital">Example:</span> "Sign up for (Your Band’s name)’s email list for a chance to win tickets to their next show. Post a link to where people sign up for your contest in exchange for signing up for something.</blockquote</p>'
    ].join(""));
    $('#ag_div_3 div').removeClass('unselected');
    $('#ag_div_3 div').addClass('selected');
    $('#ag_div_1 div, #ag_div_2 div, #ag_div_4 div, #ag_div_5 div').addClass('unselected');
  });

  $("#ag_div_4").click(function () {
    $('#div_content').html([
      '<h1>How to get Band Bucks<sup>TM</sup></h1>',
      '<h5>Headliner gets your message out to thousands of new fans.  The cost of running a promotion on Headliner is 1 Band Buck per fan reached.  Band Bucks incentivize artists to send out your message.  There are a number of different ways to earn Band Bucks:</h5>',
      '<p class="text16gray3 bold">Authorizing</p>',
      '<p class="text14gray">When you first connect your social networks to Headliner, you earn 1x Band Bucks for every fan, friend and follower you already have. So a band with 1,000 fans will receive 1,000 Band Bucks when they connect their social networking accounts to the system.</p>',
      '<p class="text16gray3 bold">Accepting Offers</p>',
      '<p class="text14gray">After you have connected your social networking accounts to Headliner, the easiest way to earn additional Band Bucks is by accepting promotions from other bands. Every time you accept a promotion, you will earn Band Bucks based on the number of fans you have. The more fans you have, the more Band Bucks you will receive every time you accept a promotion.</p>',
      '<p class="text16gray3 bold">Inviting</p>',
      '<p class="text14gray">You can earn Band Bucks by inviting other artists to use Headliner. You can invite new users to Headliner by clicking on the “Invite Bands” button on the upper right corner of the Headliner Exchange. When other artists join using your invite link, you will be credited with their number of fans in Band Bucks.</p>',
      '<p class="text16gray3 bold">Buying</p>',
      '<p class="text14gray">If you want Band Bucks immediately you can buy them. Click “Get Band Bucks” in the upper right corner of Headliner Exchange to purchase Band Bucks through Paypal or with a credit card.</p>',
      '<p class="text16gray3 bold">Subscribing</p>',
      '<p class="text14gray">When you subscribe to Headliner you gain access to analytic tools that accurately track the success of your promotion. As a subscribed user you will also receive 10,000 Band Bucks each month which is a value of $10.</p>'
    ].join(""));
    $('#ag_div_4 div').removeClass('unselected');
    $('#ag_div_4 div').addClass('selected');
    $('#ag_div_1 div, #ag_div_2 div, #ag_div_3 div, #ag_div_5 div').addClass('unselected');
  
  });//END artist guide page content

  
});
