$(function() {
	var loc = document.location.pathname;
	var pindex = loc.substring(loc.lastIndexOf('/')+1);
	var ccc= [0,1,2,3,4,5,6,7,8,9];
	var sdcref= 'http://api.soundcloud.com/tracks.json?client_id=834v4qK9N8XbZkln5Awxxw&q=IndyDistro'
	actslide= $('#selected_item').find('.slide');
	if (actslide.length >= 1){ slides(); }
	accchk = $('#selected_item').find('#accordion');
	if (accchk.length >=1) {
	  $(this).accordion({
		active: 0,
		clearStyle: true,
		fillSpace: false,
		header: 'h6',
		autoHeight: true
	  });
	};
	ilchk = $('#column2').find('#item_list');
	pwchk = $(ilchk).find('.promowr');
	ilchk.length == 1 && pwchk.length >= 1 ? slider() : tablepos();
	if ( $('.sc-player').length > 0 ){
	  bldarr = [];
	  checkbld = $('p.player.hide').length;
	  if (checkbld > 1){
		i=0;
		$.each( $('p.player.hide'), function(){								 
			blditem = $(this).text().replace(/[^a-zA-Z0-9][\s-(+]+/g,'').replace(/[\s-(/]/g,'_');
			checkbld-1 != i ? bldtagstr = blditem+'+' : bldtagstr = blditem;
			bldarr.push(bldtagstr);
		});
	  }else if (checkbld == 1){
		blditem = $('p.player.hide').text().replace(/[^a-zA-Z0-9][\s-(]+/g,'').replace(/[\s-(]/g,'_');
		bldarr.push(blditem);
	  };
	  bldstr = bldarr.join('');
	  getstrL= sdcref+'&tags='+bldstr+'&format=js&callback=?';
	  getstrS= sdcref+'+'+bldstr+'&format=js&callback=?';
	  $('.sc-player').hasClass('list') ? getstr=getstrL : getstr=getstrS;
	  //console.log(getstr)
	  aref= [];
	  $.getJSON(getstr, function(data){
		  if (data != ''){					   
			for (i=0; i < data.length; i++){
				tagstr = '<a href="'+data[i].uri+'">'+data[i].title+'</a><br/>';
				aref.push(tagstr);
			}
			$('.sc-player').append(aref.join(''));
			$.getScript('/js/sc-player.js');
			//console.log(data)
		  };
	  });
	};
	frmchk = $('#column1').find('form#contactform');
	if(frmchk.length > 0 ){ $.getScript('/js/sendit.js');}
	$('#toppromo  .promowr a').live('click',function(){return loadIntoContent(this) });
	$('a.close_link').bind('click', function(){return loadIntoContent(this);});
	$('.more').live('click', function(){return loadIntoContent(this);});
	function loadIntoContent(clicked) {
	  var source = $(clicked).attr('href');
	  var refurl = document.location.pathname;
	  $('#column2').hide().load(source,function(){ slides(); $('#column2').fadeIn(500, function(){ $('.close_link').attr('href', refurl); }) });
	  return false;
	}
	function slides(){	
		// get hero story containers
		$slides = $('#selected_item > .slide');
		// set default visible slide
		first = $slides[0];
		$(first).addClass('active');
		// hide all other slides
		for (var i=1; i<=$slides.length-1; i++){
		  start = $slides[i]	  
		  $(start).removeClass('active').hide();
		};
		// set the number of tabs based on the number of storied in the document
		tabs = [];
		for (var i = 1; i<= $slides.length; i++){
			var tab =  '<a id="tab_'+i+'" href="#"></a>';
			tabs.push(tab);
		};
		$('.hero.tabs').html( tabs.join('') );
		// get dimensions necessary for the rest of the script
		var tabdims= {
		  fwidth : parseInt($('.hero.forward').outerWidth()),
		  bwidth : parseInt($('.hero.backward').outerWidth()),
		  awidth : (parseInt($('.hero.tabs a').outerWidth()) + parseInt($('.hero.tabs a').css('marginRight') ) + parseInt($('.hero.tabs a').css('marginLeft') ))* $slides.length,
		  clwidth : parseInt($('#selected_item.overlay .close_link').outerWidth())
		};
		clchk = $('#heronav').find('.close_link');
		if (clchk.length >= 1){
		 twidth = (tabdims.awidth + tabdims.bwidth + tabdims.fwidth + tabdims.clwidth );
		}else{
		  twidth = (tabdims.awidth + tabdims.bwidth + tabdims.fwidth);	
		}
		 //dynamically set width of the tabs container
		$('.hero.tabs').css('width', tabdims.awidth );
		// dynamically set width of the heronav container
		$('#heronav').css('width', twidth + (parseInt($('.hero.tabs a').css('marginRight') )*3 ) +'px');
		// on click activity 
		tabs =$('.hero.tabs a')
		$('#tab_1').addClass('current');
		$(tabs).bind('click',function(){ 
			thisid = parseInt($(this).attr('id').split('_')[1]);
			aslide = $('#selected_item').find('div[id="hero_'+thisid+'"]');
			$('.current').removeClass('current');
			$('#tab_'+thisid).addClass('current');
			$('.active').animate({opacity: 'hide'},300,function(){
				$(this).removeClass('active');
				$(aslide).addClass('active').animate({opacity: 'show'},300);
			});
		});
		$('.hero.forward').bind('click',function(){
			s=$slides.length -1;
			actid = parseInt($('.active').attr('id').split('_')[1]);
			if (s>=actid && s<= $slides.length){							 
			  $('.active').animate({opacity: 'hide'},300, function(){ $(this).removeClass('active').next().addClass('active').animate({opacity: 'show'}, 300) });
			  $('.current').removeClass('current').next($(tabs)).addClass('current');
			}else{
			  $('.active').animate({opacity: 'hide'},300,function(){ $(this).removeClass('active'); $(first).addClass('active').animate({opacity: 'show'}, 300); });
			   $('.current').removeClass('current')
			   $('#tab_1').addClass('current');
			};						 
		 });
		$('.hero.backward').bind('click',function(){
			actid = parseInt($('.active').attr('id').split('_')[1]);
			if (actid == 1){
			 $('.active').animate({opacity: 'hide'},300,function(){ $(this).removeClass('active'); $('.slide:last-of-type').addClass('active').animate({opacity: 'show'},500); });
			 $('.current').removeClass('current')
			 $('#tab_'+$slides.length).addClass('current');
			}else{
			  $('.active').animate({opacity: 'hide'},300, function(){ $(this).removeClass('active').prev().addClass('active').animate({opacity: 'show'}, 500) });
			  $('.current').removeClass('current').prev($(tabs)).addClass('current');
			};						 
		 });
	}
	function slider(){
		var countN = parseInt($('#item_list div.promowr').length);
		// Set variable for slide interactions including width of container and limiters for end and restart
		var wrwidth = $('#item_list div.promowr').outerWidth() + parseInt($('#item_list div.promowr').css('marginRight')) + parseInt($('#item_list div.promowr').css('marginLeft'));
		var slideWidth = ((countN) * (wrwidth));
		var pgWidth = ((wrwidth) *7);
		var farRight = (slideWidth / wrwidth) / 7;
		var restart = 0;
		alphanav();
		loadpos();	
		function sortNumber(a, b){ return a > b; }
		function alphanav(){
		  uarr = []
		  numarr = []
		  $.each($('.wrlabel'), function(i){
			ind = $(this).attr('index');
			indr = parseInt($(this).attr('index'));
			$.inArray(indr,ccc) > -1 ? numarr.push(ind) : uarr.push(ind.toUpperCase());			
		  });
		  uarr = $.unique(uarr).sort(sortNumber)
		  harr = [];
		  numobj = '<a href="'+numarr[0]+'">0-9</a><p>|</p>'
		  numarr.length >= 1 ? harr.push(numobj) : numarr=0
		  $.each(uarr, function(i){
			  harr.push('<a href="'+uarr[i]+'"> '+uarr[i]+' </a><p>|</p>');			  
		  })
		  $('#alphaiwr').append(harr.join(''));
		  $('#alphaiwr a').click(function(){
			indv = $(this).attr('href');
			alphaselector = $('.wrlabel[index^="'+indv+'"]')[0];
			apar= $(alphaselector).parent()
			ali = $('#item_list .promowr').index(apar)
			alsld = ali * wrwidth;
			bysevde = (ali/7).toFixed(2);
			bysevwhl = Math.round(ali/7);
			bysev = bysevde-bysevwhl.toFixed(2)
			bysev <= .50 && bysev >= 0 ? currentPosition = bysevwhl : currentPosition = bysevwhl+1 || bysev <= .50 && bysev <= 0 ? currentPosition = bysevwhl-1 : currentPosition = bysevwhl;
			manageControls(currentPosition);
			$('#selector #item_list').animate({ 'marginLeft' : -alsld },150);
			return false;					 									 
		   });
		}
		function loadpos(){
			indexobj = $('#item_list').find('a[href="'+loc+'"]').parent();
			$('#item_list').find('a[href="'+loc+'"]').addClass('index').removeClass('hoverOff');
			sldpos = $('#item_list .promowr').index(indexobj);
			initpos = Math.round(sldpos / 7);
			initposdec= (sldpos/7).toFixed(2);
			whlck = initposdec - initpos;
			whlck <= .50 && whlck >= 0 ? initpos = initpos : initpos = initpos+1 || whlck <= .50 && whlck <= 0 ? initpos = initpos-1 : initpos = initpos;
			initpos >= 1 ? $('#selector #item_list').css({'marginLeft':( pgWidth* -initpos) }) : $('#selector #item_list').css({'marginLeft':0});
			sldpos <= 1 ? currentPosition=0 : currentPosition=initpos;
			manageControls(currentPosition);
		};		  
		$("#selector #item_list").css('width',slideWidth + "px");
		$('#tblwr').append(' <div id="mvright" class="control COL right" title="move one panel left"></div> ');
		$('#tblwr').prepend(' <div id="mvleft" class="control COL left" title="move one panel right"></div> ');
		manageControls(currentPosition);
		// Bind Click to Control, when clicke Current Position increases&/decreases in a +1 state both left and right controls are visible. 
		$('.control.COL').bind('click', function(){
			// Determine new position
			currentPosition = $(this).attr('id')=='mvright' ? currentPosition+1 : currentPosition-1;
			// Hide / show controls
			manageControls(currentPosition);
			// Move .arearow using margin-left
			$('#selector #item_list').animate({
			'marginLeft' : ((pgWidth))*(-currentPosition)
			},150);
			bysev = 0
		  });
		  // Show, Hide and Callback based on limiters
		  function manageControls(position){
		  
			if(position==0){ $('#mvleft').removeClass('bk') } else{ $('#mvleft').addClass('bk') }
			
			if(position>=farRight){ 
			  $('#selector #item_list').animate({ 'marginLeft' : restart },0), currentPosition=0; 
			  manageControls(currentPosition);
			}
		};
		$('.promowr').hover(
			function() { 
					stateob = $(this).find('.wrlabel');
					if ( $(stateob).hasClass('hoverOff')){
						$(stateob).removeClass('hoverOff');	
					}
			},
			function() {      
				  stateob = $(this).find('.wrlabel') 
					if ( $(stateob).hasClass('index')  ) {
						$(stateob).removeClass('hoverOff');	
					}else{
						$(stateob).addClass('hoverOff');
					}
			}
		);

   };   
  function tablepos(){
	indexobj = $('#item_list #itemwr').find('a[href="'+loc+'"]');
	indexobj.length >=1 ? tpos = $(indexobj).position().top : tpos = 0;
	$('#item_list').scrollTop(tpos);
	$(indexobj).addClass('active');
	actsrt = $('#selector').find('a.sort_selector[index="'+pindex+'"]');
	crtcheck = $('#selector a.sort_selector.sorted');
	sortarr = ['catnum','artist','name','label','genre']
	pindex != crtcheck && pindex != 'catnum' ? $(actsrt).addClass('sorted') && $(crtcheck).removeClass('sorted') : $('#sort_catnum').addClass('sorted');
  };
 $.each($('a.bitly.hide'), function(){
		$this = $(this)					   					   
		objURL= 'http://'+$this.text().trim();
		bitlyM(objURL,$this);
 });
 function bitlyM(URL,obj){
 // For the purpose of shortening URLS
 // set up default options
  var bitset = {
    version:    '2.0.1',
    login:      'guyfriday',
    apiKey:     'R_8b61bf46fac5d00d5a1028f512d0630d',
    history:    '0',
    longUrl:    URL
  };
  // Build the URL to query
  var daurl = "http://api.bit.ly/shorten?"
    +"version="+bitset.version
    +"&longUrl="+bitset.longUrl
    +"&login="+bitset.login
    +"&apiKey="+bitset.apiKey
    +"&history="+bitset.history
    +"&format=json&callback=?";
    // Utilize the bit.ly API
    $.getJSON(daurl, function(data){
        // Make a good use of short URL
        bitr = data.results[bitset.longUrl].shortUrl;
		bitrstr = bitr.split('//')[1];
		$(obj).attr('href',bitr).text(bitrstr).removeClass('hide');
    });
 }
 
});
