soundManager.flashVersion = 9;
soundManager.useConsole = true;
soundManager.consoleOnly = true;
soundManager.debugMode = false;
soundManager.defaultOptions.multiShot = false;
soundManager.url = "/swf/soundmanager2.swf";
// soundManager.useHighPerformance = false;

//if(!(navigator.userAgent.search(/applewebkit/i) != -1 && navigator.userAgent.search(/(mobile)/i) == -1)) {
//  soundManager.useHTML5Audio = true;
//}

function windowSizeCheck(){
	var width = $(window).width();
  if(width < 1150){
		$(".cities li .city-header a.city-name").css("font-size", "23px").css("margin", "11px 0 0 10px");
	}else if(width < 1300){
		$(".cities li .city-header a.city-name").css("font-size", "28px").css("margin", "8px 0 0 10px");
	}else if(width > 1400){
		$(".cities li .city-header a.city-name").css("font-size", "32px").css("margin", "5px 0 0 10px");
	}
}

function mark_tab_as_playing(state){
  if (!jQuery.browser['msie']){
    s = $("title").html();
    marker = 'NOW PLAYING: ';
    if(state){
      if (s.indexOf(marker) == -1)
        s = marker+s;
    }else{
      if (s.indexOf(marker) != -1)
          s = s.substring(12);
    }

    $("title").html(s);
  }
}

function soundcloud_api_url(id) {
    return "http://api.soundcloud.com/tracks/" + id + ".js?callback=?";
}

function capitalize(s){
  if (s && s.length > 0){
    s = s.substring(0,1).toUpperCase() + s.substring(1);
    return (s + ", ");
  }else{
   return "";
 }
}

$(document).ready(function() {	
  
	windowSizeCheck();
	$(window).resize(function(){
		windowSizeCheck();    
	});
	  
   $(".cities li").show();
   var bodyId = $("body").attr("id");

  
  // Make all more-tracks links invisible
  $(".more-tracks").animate({"opacity": 0}, 0, "");
  

  if(bodyId == "cities-show"){
    $("#city-expanded-header").animate({"opacity": 1}, 1000, "easeinout");
    $("#playlist-menu").animate({"opacity": 1}, 2000, "easeinout");
    $("#playlists").animate({"opacity": 1, "height": "333px"}, 350, "", function(){
      $("#adsense-container img").fadeIn(1000);
    });
  }
  
  // CITY EXPANDED PLAYLIST (TODO: fix inheritance)
  $("#playlists ol li").live('click',function(e) {
    if(!$(e.target).hasClass("soundcloud-link")){
      var self = this;
      var track_id = $(this).attr("id").replace(/^.*[\_\\]/g, '');
  	  var url = soundcloud_api_url(track_id);
  
      if($(self).hasClass("playing")){ // if track is playing, pause it
        stop();
        mark_tab_as_playing(false);
        $(self).removeClass("playing").addClass("paused");
        
        // Remove highlight of playlist title when paused
        $(".list-marked").removeClass("list-marked");      
          
      }else{
          $.jsonp({
                url: url,
                error: function(xOptions, textStatus) {
                    if (textStatus === "error") {
                        $.post("/tracks/mark_invalid", {track_id: track_id});
                        $(self).slideUp("slow", function() {
                            if ($(self).next() != 0) {
                                $(self).next().click(); // play next if exists
                            } else {
                                //Remove the Now playing string if end of list
                                $(self).parent().parent().find(".track-playing").recover().hide();
                            }
                            $(self).remove();
                        });
                    }
                },
                success: function(track) {
  
                  stop();
                  
                  // Register a new play when a new track is played
                  if ($(self).attr("class") === ''){
                    $.post("/play/new", {track_id: track_id, city_id: city_id})
                  }
                                    
                  // Graphics
                  $(".paused").removeClass("paused");
                  $(".playing").removeClass("playing");
                  $(self).addClass("playing");
                  mark_tab_as_playing(true);
  
                  $(self).find(".soundcloud-player").addClass("playing");
  
                  // Sound
                  sound = soundManager.createSound({
                    id: track.id,
                    url: track.stream_url,
                    whileloading : throttle(200,function() {
                      //loading.css('width',(sound.bytesLoaded/sound.bytesTotal)*100+"%");
                    }),
                    whileplaying : throttle(200,function() {
                      //progress.css('width',(sound.position/sound.durationEstimate)*100+"%");
                      //$('.position',dom).html(formatMs(sound.position));
                      //$('.duration',dom).html(formatMs(sound.durationEstimate));
                    }),
                    onfinish : function() {
                      if($(self).next() != 0) {
                        $(self).next().click(); // play next if exists
                      }
              
                      //Remove playing icon when track changes
                      $(self).removeClass("playing");
                      $(self).find(".soundcloud-player").removeClass("playing");
  
                    },
                    onload : function () {
                      //loading.css('width',"100%");
                    }
                  });
          
                  var trackInfo = $("#track-info").clone().show();
                  $("#track-info").remove();
                  trackInfo.find("#genre").html(capitalize(track.genre));
                  trackInfo.find("#playcount").html(track.playback_count + " plays");
                  trackInfo.appendTo($(self).find("a.soundcloud-player"));
          
                  // Mark the list header if list is playing/paused
                  $(".list-marked").removeClass("list-marked");
                  $("#" + $(self).closest("ol").attr("class").split(" ")[0] + " a").addClass("list-marked");
        
                      play();
                  }
              });
          }
          return false;
      }
  });
  
  //Check browser
  if (jQuery.browser['msie']){
    if (jQuery.browser['version'] < 7) $('#browser-disclaimer').html(' Dear IE6 user, CitySounds is limited in your browser. Please upgrade or <a href="http://getfirefox.com">change browser</a>');
  }
  


  var sound; // empty sound
  
  // LATEST CHART PLAYLIST
  $("ol.playlist li").live('click',function(e) {
      if (!$(e.target).hasClass("soundcloud-link")) {
          var self = this;
          var track_id = $(this).attr("id").replace(/^.*[\_\\]/g, '');
          var url = soundcloud_api_url(track_id);
          $(".track-playing").recover().hide();

          if ($(self).hasClass("playing")) { // if track is playing, pause it
              stop();
              $(self).removeClass("playing").addClass("paused");        
              $(self).parent().closest("li").find(".track-playing").recover().hide(); //remove now playing string
              mark_tab_as_playing(false);
          } else {
              $.jsonp({
                  url: url,
                  error: function(xOptions, textStatus) {
                      if (textStatus === "error") {
                          $.post("/tracks/mark_invalid", {track_id: track_id});
                          $(self).slideUp("slow", function() {
                              if ($(self).next() != 0) {
                                  $(self).next().click(); // play next if exists
                              } else {
                                  //Remove the Now playing string if end of list
                                  $(self).parent().parent().find(".track-playing").recover().hide();
                              }
                              $(self).remove();
                          });
                      }
                  },
                  success: function(track) {
                      stop();

                      // Register a new play when a new track is played
                      if ($(self).attr("class") === ''){
                        var city_id = $(self).parent().parent().parent().attr('id').replace("city_","");
                        $.post("/play/new", {track_id: track_id, city_id: city_id})
                      }

                      // Graphics
                      $(".paused").removeClass("paused");
                      $(".playing").removeClass("playing");
                      $(self).addClass("playing");
                      mark_tab_as_playing(true);

                      $(self).find(".soundcloud-player").addClass("playing");
                      $(self).parent().closest("li").find(".track-playing").fadeIn(1000, function(){$(this).pulse({opacityRange: [0.95, 0.2], speed: 700})});

                      // Sound
                      sound = soundManager.createSound({
                          id: track.id,
                          url: track.stream_url + "?oauth_consumer_key=pkRZOuBMvD0vNrxQPoIxg",
                          whileloading : throttle(200,function() {
                            //loading.css('width',(sound.bytesLoaded/sound.bytesTotal)*100+"%");
                          }),
                          whileplaying : throttle(200,function() {
                            //progress.css('width',(sound.position/sound.durationEstimate)*100+"%");
                            //$('.position',dom).html(formatMs(sound.position));
                            //$('.duration',dom).html(formatMs(sound.durationEstimate));
                          }),
                          onfinish : function() {
                              if ($(self).next() != 0) {
                                  $(self).next().click(); // play next if exists
                              } else {
                                  //Remove the Now playing string if end of list
                                  $(self).parent().parent().find(".track-playing").recover().hide();
                              }
                              //Remove playing icon when track changes
                              $(self).removeClass("playing");
                              $(self).find(".soundcloud-player").removeClass("playing");
                          }
                      });
                      play();
                  }
              });
          }
          return false;
      }
  });


  var play = function() {
    if(sound) {
      sound.paused ? sound.resume() : sound.play();
    }
  };
  
  var stop = function() {
    if(sound) {
      sound.pause();
    }
  };
	
  // throttling function to minimize redraws caused by soundmanager
  var throttle = function(delay, fn) {
    var last = null,
        partial = fn;

    if (delay > 0) {
      partial = function() {
        var now = new Date(),
            scope = this,
            args = arguments;

        // We are the last call made, so cancel the previous last call
        clearTimeout(partial.futureTimeout);

        if (last === null || now - last > delay) { 
          fn.apply(scope, args);
          last = now;
        } else {
          // guarentee that the method will be called after the right delay
          partial.futureTimeout = setTimeout(function() { fn.apply(scope, args); }, delay);
        }
      };
    }
    return partial;
  };

	// Events
	$('.email-field').bind('focus', function(e){
    if ($(this).attr('value') === 'Your email...') $(this).attr('value', '');
  });
  $('.email-field').bind('blur', function(e){
    if ($(this).attr('value') === '') {
      $(this).attr('value', 'Your email...');
    }
  });
	
	$(".city-header").bind("click", function(e){
	 
	  if(!$(e.target).hasClass("menu-link")){ 	  
		  var city = $(this).parent();
		  var opened = $(".opened");
		  
		  if(!city.hasClass("opened")){
		  	//Close other open city
		    opened.find("img.city-image").animate({height:"40px",width:"40px"},300, "easeinout");
		  	opened.animate({height: "50px"}, 500, "easeinout", function(){
  	  		opened.removeClass("opened");
		  	});
		  	opened.children(".city-info").fadeOut(500);
		  	opened.find(".more-tracks").animate({"opacity": 0}, 100, "easeinout");
		  	
		  	//Slide open the city
		  	city.find("img.city-image").animate({height: "75px", width: "75px"}, 300, "easeinout");  			  
		  	city.animate({height: "285px"}, 500, "easeinout");
		  	city.children(".city-info").fadeIn(500);
		  	city.find(".more-tracks").animate({"opacity": 1}, 1000, "easeinout");
		  	city.addClass("opened");
        
        city.find("ol li a:first").click(); // start playing first track
		  }
		  return false;
	  }
	});

  $(".cities li.city").hover(function(e){
    var city = $(this);
		var opened = $(".opened");
		city.find(".city-header a.city-name").addClass("glow");
		
  },
  
  function(e){
    var city = $(this);
		var opened = $(".opened");
		city.find(".city-header a.city-name").removeClass("glow");
						
  });

  $("#city-expanded #playlist-menu li").bind("click", function(){
    if(!$(this).hasClass("chosen")){
      var listClass = $(this).attr("id");
      
      $("#city-expanded #playlists ol").hide();
      $("."+listClass).fadeIn(750);
      
      $(".chosen").removeClass("chosen");
      $(this).addClass("chosen");
    }
     return false;
  });
  
    
  $("a.fb-share").click(function(){
    window.open(this.href,'Share on Facebook','width=620,height=320');
		$.post('/facebookshares/register' + window.location.pathname); // pathname innehåller redan snedstreck
		return false;
  });  
  
  $("#about-link").click(function(){
    $("#close-link").fadeIn(400);
    $("#about-screen>div").fadeIn(400);
    $("#about-screen").animate({height: $(document).height() + "px", opacity: 0.97}, 500, "easeinout");
    return false;
  });
  
  $("#close-link").click(function(){
    $("#close-link").fadeOut(400);
    $("#about-screen>div").fadeOut(400);
    $("#about-screen").animate({height: 0, opacity: 0.8}, 500, "easeinout", function(){
      $(this).hide();
    });
    return false;
  });
  
  
  $(document).keydown(function(e) {
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
       if((key == 27)){
         $("#about-screen").animate({height: 0}, 500, "easeinout", function(){
           $(this).hide();
         });
       }
   });
   
   
  $("#city-expanded .city-image").hover(function(){
      $(this).find(".caption").stop().animate({"opacity": 0.9}, 500, "");
    },
    function(){
      $(this).find(".caption").stop().animate({"opacity": 0.5}, 500, "");
    
    });

  $("ul.avatars img").error(function () {
    $(this).unbind("error").attr("src", "http://static.twitter.com/images/default_profile_normal.png");
  });
});


 /*
  * jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php
  *
  * Uses the built in easing capabilities added in jQuery 1.1
  * to offer multiple easing options
  *
  * Copyright (c) 2007 George Smith
  * Licensed under the MIT License:
  *   http://www.opensource.org/licenses/mit-license.php
  */

/* Extending jQuery easing functions here with the one required for the player */

jQuery.easing = jQuery.extend({
	easeinout: function(x, t, b, c, d) {
		if (t < d/2) return 2*c*t*t/(d*d) + b;
		var ts = t - d/2;
		return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;		
  }
},jQuery.easing);
