// JavaScript Document

$().ready(init);

function init(){
	
  $('#audioDemo').hide(); // hide the audio demo until soundcloud resolves
	featuredArtist(); // set up the featured artist box
  sndCld.load(); // load soundcloud
  userTweet.load(); // load artist last tweet
  fifthEleFB.load(); // load artist last fb status
	
}

// Page cookies

// create cookie function
function createCookie(name,value,days) {  // create cookie by calling function with name, value and expiration in days arguments
	if (days) { // if days variable has been given a value
		var date = new Date(); // create new date object
		date.setTime(date.getTime()+(days*24*60*60*1000)); // use days to set expiration date
		var expires = "; expires="+date.toGMTString(); // create variable to hold expiration date/time - also converts expiration time to GMT string
	}

	else var expires = ""; // else set expiration to end of session
	document.cookie = name+"="+value+expires+"; path=/"; // create cookie
}

// read cookie function
function readCookie(name) {
	var nameEQ = name + "="; // create variable to read cookie name and concatenate an =
	var ca = document.cookie.split(';'); // split cookie into parts at each semi-colon and create array
	for(var i=0;i < ca.length;i++) { //  loop through array and return value of name
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// erase cookie function
function eraseCookie(name) {
	createCookie(name,"",-1);  // set expiration date to negative number to instantly delete cookie
}


/*****************************************************************
******************************************************************/

// Stylesheet switching scripts

// set variables for selecting stylesheet and header images
var curStyle;
var curLogo;
var curStrapLine;
var curHeadTitleImg;
var likeInfo;

// style selector function
function stylePick(styleChoice){ // stylechoice variable passed a value by onclick event
	var curStyle 		= document.getElementById("styleSheet"); // get the current stylesheet
	var curLogo 		= document.getElementById("headerlogo"); // get the main header logo
	var curStrapLine 	= document.getElementById("headertext"); // get the main header strapline
	var curHeadTitleImg = document.getElementById("headertitle"); // get the header title text img
	var likeInfo 		= document.getElementById("likeInfo"); // get facebook like element 
	
	curStyle.href = "../assets/css/styles" + styleChoice + ".css"; // change the current style sheet
	curLogo.src = "../assets/images/logos/5thlogo-" + styleChoice + ".jpg"; //  change the header logo
	curStrapLine.src = "../assets/images/logos/strap-text-" + styleChoice + ".jpg"; // change the header strapline
	
	if (styleChoice == 'hc'){ // if selected style choice is hc
		curHeadTitleImg.src = '../assets/images/logos/5th-title-hc.jpg'; // change the header title text img
		likeInfo.setAttribute('colorscheme', 'dark');
	} else {
		curHeadTitleImg.src = '../assets/images/logos/5th-title.jpg'; // or else set the default title text img
		
		likeInfo.setAttribute('colorscheme', 'light');
	};
	createCookie('myStyleChoice', styleChoice, 365); // create a cookie to store the stylesheet choice 
	createCookie('keepLogo', styleChoice, 365); // create a cookie to store the header logo choice
}

if (readCookie('myStyleChoice')){ // see if style choice cookie exists
	var myStyle = readCookie('myStyleChoice');
	document.getElementById("styleSheet").href = "../assets/css/styles" + myStyle + ".css"; // set style sheet based on cookie 
};

// onload function to load cookies after page loads so as to change header images
function loadCookies(){
	var keepLogo 		= readCookie('keepLogo');
	var bodyTextSize 	= readCookie('textSize');
	var likeInfo 		= document.getElementById("likeInfo"); // get facebook like element 
	
	if (keepLogo){ // if header logo cookie exists
		document.getElementById("headerlogo").src = "../assets/images/logos/5thlogo-" + keepLogo + ".jpg"; // change the header logo
		document.getElementById("headertext").src = "../assets/images/logos/strap-text-" + keepLogo + ".jpg"; // change the header strapline
		
		
		if (keepLogo == 'hc'){ // if the logo cookie value is hc 
			document.getElementById("headertitle").src = "../assets/images/logos/5th-title-hc.jpg"; // set the title text img to the hc version
			
			likeInfo.setAttribute('colorscheme', 'dark');
		} else {
			document.getElementById("headertitle").src = '../assets/images/logos/5th-title.jpg'; // else load the default title text img version
			
			likeInfo.setAttribute('colorscheme', 'light');
		};
	};
	
	if (bodyTextSize){ // Check to see if text size cookie exists
		var textSizeLink = document.getElementById("textlga");
		document.body.style.fontSize = bodyTextSize; // set the default body text size
		
		if (bodyTextSize == '16px'){ // if value stored is 16px
			textSizeLink.style.backgroundImage = 'url(../assets/images/textsmimg.gif)'; // change text size image
			textSizeLink.onclick = function (){smallerText()}; // change text size onclick event
		} else {
			textSizeLink.style.backgroundImage = 'url(../assets/images/textlgimg.gif)'; // change text size image
			textSizeLink.onclick = function (){biggerText()}; // change text size onclick event
		};
	};
}

/*****************************************************************
******************************************************************/

// Text Size functions

// Make text bigger
function biggerText(){
	var textSizeLink = document.getElementById("textlga");
	// set body font size to 16px
	document.body.style.fontSize = '16px';
	// change font size link image
	textSizeLink.style.backgroundImage = 'url(../assets/images/textsmimg.gif)';
	// set onclick event to run smaller text function
	textSizeLink.onclick = function (){smallerText()};
	// create cookie to store text size
	createCookie('textSize', '16px', 365);
}

// Make text bigger
function smallerText(){
	var textSizeLink = document.getElementById("textlga");
	// set body font size to 12px
	document.body.style.fontSize = '12px';
	// change font size link image
	textSizeLink.style.backgroundImage = 'url(../assets/images/textlgimg.gif)';
	// set onclick event to run bigger text function
	textSizeLink.onclick = function (){biggerText()};
	// create cookie to store text size
	createCookie('textSize', '12px', 365);
}


/*****************************************************************
******************************************************************/

//  Funtion for loading XML docs

function loadXMLDoc(dname) {
	// Import Featured artist profile info
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
  		xmlhttp=new XMLHttpRequest();
  	} else {
		// code for IE6, IE5
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 	}
	xmlhttp.open("GET",dname,false); // Open required xml doc
	xmlhttp.send(null);
	return xmlhttp.responseXML;
}

/*****************************************************************
******************************************************************/

//  Featured artist information

function featuredArtist(){
	
	// Import Featured artist profile info
	xmlDoc = loadXMLDoc("../assets/xml/featuredartist.xml"); 

	var featArtists = xmlDoc.getElementsByTagName("artist");
	var featArtIndex = Math.floor(Math.random()*featArtists.length);
	var artistName = (featArtists[featArtIndex].getElementsByTagName("name")[0].childNodes[0].nodeValue);
	var artistImg = (featArtists[featArtIndex].getElementsByTagName("photo")[0].childNodes[0].nodeValue);
	var artistImgAlt = artistName;
	var featArtImgHeight = (featArtists[featArtIndex].getElementsByTagName("height")[0].childNodes[0].nodeValue);
	var artistLoc = (featArtists[featArtIndex].getElementsByTagName("location")[0].childNodes[0].nodeValue);
	var artistBlurb = (featArtists[featArtIndex].getElementsByTagName("blurb")[0].childNodes[0].nodeValue);
	
  var featured = document.getElementById("featured");
  
	if (featured) {
    
      document.getElementById("featured").innerHTML = '<div id="feattitle"><h2>Featured Artist</h2></div><div id="featimg"><a href="../html/' + artistImg + '.html"><img src="../assets/images/featured/' + artistImg + '-feat.jpg" width="150px" height="' + featArtImgHeight + '" alt="' + artistImgAlt + '" /></a></div><h3><a href="../html/' + artistImg + '.html">' + artistName + '</a></h3><p><strong>Based in:</strong> ' + artistLoc + '</p><p>' + artistBlurb + '</p>';

  }
	
}

/*****************************************************************
******************************************************************/

//  Newsletter form validation

function checkForm() {
	// For each item in the fieldstocheck array
  for (i=0;i<fieldstocheck.length;i++) {
		// Check if required field is a checkbox....
    if (eval("document.subscribeform.elements['"+fieldstocheck[i]+"'].type") == "checkbox") {
		// if it is a checkbox and the box is checked, move on
      if (document.subscribeform.elements[fieldstocheck[i]].checked) {
      } else {
		  // else ask for field to be completed 
        alert("Please enter your "+fieldnames[i]);
        eval("document.subscribeform.elements['"+fieldstocheck[i]+"'].focus()");
        return false;
      }
    }
	//  If required field is not a checkbox....
    else {
		// Check if required field is empty
      if (eval("document.subscribeform.elements['"+fieldstocheck[i]+"'].value") == "") {
		  // if the field is empty, ask for input
        alert("Please enter your "+fieldnames[i]);
        eval("document.subscribeform.elements['"+fieldstocheck[i]+"'].focus()");
        return false;
      }
    }
  }
  //  Check to see if entered emails match  
  if(! compareEmail())
  {
	  //  If compareEmail returns false give error message
    alert("Email Addresses you entered do not match");
    return false;
  }
  // If all has gone well, return true
  return true;
}

var fieldstocheck = new Array();
var fieldnames = new Array();

//  function to convert variables for use in checkForm function
function addFieldToCheck(value,name) {
  fieldstocheck[fieldstocheck.length] = value;
  fieldnames[fieldnames.length] = name;
}

//  Compare email address input by user to see if they match
function compareEmail()
{
  return (document.subscribeform.elements["email"].value == document.subscribeform.elements["emailconfirm"].value);
}

//  Add onclick functionality to submit button for IE and other browsers
function AddEventListener(element, eventType, handler, capture)
{
	if (element.addEventListener)
	// If browser supports addEventListener, the add onclick functionality added below in window.onload function
		element.addEventListener(eventType, handler, capture);
	else if (element.attachEvent)
	// If browser supports attachEvent, the add onclick functionality added below in window.onload function
		element.attachEvent("on" + eventType, handler);
}

//  On window load, pass arguments to AddEventListener function - 	NOT BEING CALLED!!!!!!!!!
window.onload = function()
{
	AddEventListener(document.getElementById("submitbtn"), "click", checkForm, false);
}

/*****************************************************************
 * Twitter Posts
******************************************************************/


userTweet = {
  load: function() {
    var $artist = $('#twitterName').text();
    
    if ($artist != '') {
      this.getTweet($artist);
    }
  },
  getTweet: function($artist) {
    
    var url='http://api.twitter.com/1/statuses/user_timeline/' + $artist + '.json?callback=?&count=1'; // make the url
    var _userTweet = this;
    
    $.getJSON(url, function(tweet){ // get the tweets
      _userTweet.addTweet(tweet[0]);
    });
  },
  addTweet: function($data) {
    
    var created_at = $data.created_at.split('+');
    created_at = $.trim(created_at.shift());
    created_at = created_at.slice(3);
    created_at = created_at.slice(0, -3);
    
    var tweet = convertURLs($data.text);

    $('<div id="tweet"><img src="../assets/images/sn_icons/bird.jpg" alt="Latest Tweet" width="50" height="33" />' + tweet + '<br /><span id="tweetDate">- ' + created_at + '</span></div>')
    .insertAfter('#snBox'); // get the first tweet in the response and place it inside the div
    
  }
}

/*****************************************************************
 * FB Page Posts
******************************************************************/

fifthEleFB = {
  accessToken: 'AAACXNZCGpXaIBAJaba4ZAAoVZAu1HjCjML0CIbHsBkVk6KUjepyJ7CdIa6M7n1cnEg2nyvDHvG6y0hH165CMDFDBO5HB6wZD',
  load: function() {
    var $artist = $('#fbPageName').text();
    
    if($artist != ''){
      $('#likeBox').remove(); // remove the default facebook like box
      this.loadPublicFBData($artist);
      this.loadPagePost($artist);
    }
    
  },
  loadPublicFBData: function($artist) {
    var _feFB = this;
    var _artist = $artist;
    var $url = 'https://graph.facebook.com/' + $artist;
    
    $.ajax({
      type: 'get',
      dataType: 'json',
      url: $url,
      success: function($data) {

        _feFB.display($data, _artist);

      },
      error: function($data) {
        console.log($data);
      }
    });
  },
  display: function($data, $artist) {
    $('<div id="fbPageInfo"><h2><a href="' + $data.link + '" target="_blank">' + $data.name + ' Latest Facebook Status</a></h2><a href="' + $data.link + '" target="_blank"><img src="' + $data.picture + '" id="fbPageImg" /></a><p id="moreInfoFB"><a href="' + $data.link + '" target=_blank">Go to facebook page</a></p><p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="https://www.facebook.com/' + $artist + '" width="288" id="likeInfo" colorscheme="light"></fb:like></p></div>')
      .insertBefore('#googlead');
      
  },
  loadPagePost: function($artist) {
    var _feFB = this;
    var $url = 'https://graph.facebook.com/' + $artist + '/statuses?&limit=1&access_token=' + this.accessToken;
    
    $.ajax({
      type: 'get',
      dataType: 'json',
      url: $url,
      success: function($data) {
        _feFB.displayPost($data);

      },
      error: function($data) {
        console.log($data);
      }
    });
  },
  displayPost: function($data) {
    
    var data = $data.data[0];
    
    $.ajax({
      type: 'get',
      dataType: 'json',
      url: '../../html/time.php?date=' + data.updated_time,
      success: function($date) {
        var $message = data.message;
        $message = convertURLs($message); // convert urls in text to links
        
        $('<apan id="fbPagePost">' + $message + '<span id="fbPostDate">' + $date + '</span></span>')
        .insertBefore('#moreInfoFB');
      }
    })
  }
}

/*****************************************************************
 * Soundcloud
******************************************************************/

sndCld = {
  load: function() {
    
    var $artist = $('#scName').text();
    
    if($artist != ''){ // if the artist has a soundcloud page
      this.init($artist); // run the sc set up
    } else {
      if ($('#audioDemo')){ // if there is an audio demo available...
        $('#audioDemo').show(); // show the audio demo
      }
    }
    
  },
  init: function($artist) {
    
    this.initSC();
    this.getTrk($artist);
    
  },
  initSC: function($artist) {
    SC.initialize({
      client_id: "1a9cc33379fa631ae1d49e7a232909ad",
    });
  },
  getTrk: function($artist) {
    var _sndCld = this;
      
    // get the last track uploaded by artist
    SC.get("/users/" + $artist + "/tracks.json?limit=1", function(latestTrack){
      if (latestTrack != '') { // if a track object is returned...
        _sndCld.putTrk(latestTrack); // run putTrk
      } else { // else if now track object is returned
        if ($('#audioDemo')){ // if there is an audio demo available...
          $('#audioDemo').show(); // show the audio demo
        }
        
        console.log('The user has not uploaded any tracks to Soundcloud');
      }
    });
  },
  putTrk: function($data) {
    
    var trackUrl = $data[0]['permalink_url']; // store the retrieved track url

    // Use the track url to grab the embed data from Soundcloud
    SC.get("/oembed?format=json&url=" + trackUrl, function(data){
      
      var scPlayer = data['html']; // Store the embed code retrieved
      console.log(scPlayer);
      if (scPlayer !='') { // If the player object has been retrieved...
        if ($('#audioDemo')) {
//          $('#audioDemo').hide();
          
          // Create the markup for the embedded player, and insert to page.
          $('<div id="latestSCTrack"><h3>Latest Track on Soundcloud</h3>' + scPlayer + '</div>').insertAfter('#artistSite'); 
        }
      } else {
        $('#audioDemo').show();
      };
      
    });
  }
}

/*****************************************************************
 * long biogs
******************************************************************/

$(document).ready(function() {
  
  var $longBiog = $('#longBiog');
  var $parasToHide = $longBiog.find('p:not(:first)');
  
  $parasToHide.hide();
  $longBiog.append('  <a href="#" id="biogMore">Read more of this biog...</a>');
  
  var $readMore = $longBiog.find('a:last');
  
  $readMore
  .click(function(e) {
    $parasToHide.slideToggle('fast');
    
    e.preventDefault();
  })
  .toggle(function() {
    $(this).text('Read less');
  }, function() {
    $(this).text('Read more ...');
  });
})

/*****************************************************************
 * Convert url to link
******************************************************************/

function convertURLs(string) {
  string = string.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(url) {
      return '<a href="' + url + '" target="_blank">'+url+'</a>';
    });
  return string;
};
