// scott main dot com
//
// javascript for swapping a background image upon click

var image_cookie = "scottmain_image" + "=";
var image = getCookie(image_cookie);     // get the image cookie
if (image) makeStyle(image);            // if there's a cookie, then set the image

/* 
 * the real style swapping action.
 * 
 * params
 *  new_sheet - the name of the style sheet to swap in
 */
function makeStyle(new_sheet) {
	console.log(new_sheet);
	var current_sheet_link = getCurrentSheet();
	
	current_sheet_link.setAttribute("href", "/css/" + new_sheet + ".css");  // set the current stylesheet to be an alternative
	
	document.cookie = image_cookie + new_sheet;        // and set our cookie
	console.log(current_sheet_link);
}

/* 
 * retrieves my stylesheet cookie
 */
function getCookie(cookiename) {
	if (document.cookie) {                                             // if there is a cookie object
		for (var i = 0; i < document.cookie.length; i++) {             // loop through the cookie object
			var offset = i + cookiename.length;                        // the index of where my cookie's VALUE starts
			if (document.cookie.substring(i, offset) == cookiename) {  // if the string between the string between the current index and the offset is my cookie name
				var endindex = document.cookie.indexOf(";", offset);   // get the index of where my cookie's VALUE ends
				if (endindex == -1) {                                  // ...and if it's -1, then it's the last cookie
					endindex = document.cookie.length;                 // so there's no ';' and the endinex is the end of the cookie
				}
				
				return document.cookie.substring(offset, endindex);    // get and return the string that exists between the index of where my cookie's VALUE starts and the index of where it ends
			}
		}
	} else {
		return null;                                                   // if there is no cookie
	}
}

/* 
 * retrives the primary stylesheet link object from the HTML header
 */
function getCurrentSheet() {
	var links = document.getElementsByTagName("link");      // get all link objects

	for (var i = 0; i < links.length; i++) {                // loop through all the link objects found
		if((links[i].getAttribute("rel") == "stylesheet") && (links[i].getAttribute("title") != "primary")) {  // and find one that's a stylesheet (not an alternative)
			var sheet = links[i];                           // and set the object to a variable
			break;
		}
	}
	return sheet;                                           // and return that object
}