/*
	Website 23.0 (Scott Bradford: Off on a Tangent)
	Copyright (c) 1995-2011, Scott Bradford Creative Enterprises
*/

// The 'Off on a Tangent' scripts assume that jQuery, ThickBox, and JSON functions have been loaded previously

// establish the ooat object, mobile object, settings object, and image randomizer vars
ooat = {
	mobile: {},
	settings: {},
	status: {},
	maximg: 18,
	photos: [],
	holiday: {}
};

// return a random number (to make IE behave on AJAX reqests)
ooat.rand = function() {
	var rnum = (Math.floor(Math.random()*9999)).toString();
	return rnum;
}

ooat.getJsonCookieByName = function(cookieName) {
	
	// cookie content holder
	var cookieContent = {},
	    cookieTemp = '',
	    cookieStart = 0,
	    cookieEnd = 0;
	
	// if there's a cookie with the defined name, get it
	if (document.cookie.indexOf(cookieName) != -1) {
		cookieStart=(document.cookie.indexOf(cookieName))+(cookieName.length+1);
		cookieEnd=document.cookie.indexOf(";",cookieStart);

		if (cookieEnd == -1) {
			cookieEnd = document.cookie.length;
		}
		
		// unescape the encoded cookie
		cookieTemp = unescape(document.cookie.substring(cookieStart,cookieEnd));
		
		// if the cookie is valid, parse the JSON... if not, create an empty holder
		try {
			cookieContent = JSON.parse(cookieTemp);
		} catch(exception) {
			// nothing
		}
	}

	// pass back the cookie content (or an empty container)
	return cookieContent;
}

// function to load or create the ooat settings cookie (self-executing on initial load)
ooat.cookieParse = function(){
	
	// grab the cookie content
	var cookieContent = ooat.getJsonCookieByName('ooat_settings');
	
	// update old versions of the cookie as-needed
	
	// Cookie v1 (old browserType value); just destroy it (will build new cookie from scratch)
	if (document.cookie.indexOf('browserType') != -1) {
		document.cookie = 'browserType=; expires=Thu, 01-Jan-70 00:00:01 GMT'; 
	}
	// Cookie v2 (no version number, but pin is set); it's on the wrong domain, so destroy it (will be rebuilt and carry settings forward)
	if ((cookieContent.ver === undefined) && (cookieContent.pin !== undefined)) {
		document.cookie = 'ooat_settings=; expires=Thu, 01-Jan-70 00:00:01 GMT'
	}
	
	// Cookie v3; no changes necessary; just added qcp value
	
	// import the settings or establish new ones if they don't exist (or if they aren't what we expect)
	
	// font size value
	if (typeof cookieContent.fsz == "number") {
		ooat.settings.fsz = cookieContent.fsz;
	} else {
		ooat.settings.fsz = 12;
	}
	
	// menu pinning value
	if (typeof cookieContent.pin == "boolean") {
		ooat.settings.pin = cookieContent.pin;
	} else {
		ooat.settings.pin = true;
	}
	
	// mobile fixation value
	if (typeof cookieContent.mob == "string") {
		ooat.settings.mob = cookieContent.mob;
	} else {
		ooat.settings.mob = "none";
	}
	
	// quotes paused value
	if (typeof cookieContent.qcp == "boolean") {
		ooat.settings.qcp = cookieContent.qcp;
	} else {
		ooat.settings.qcp = false;
	}
	
	// current settings/cookie version
	ooat.settings.ver = 4;
}();

// function to build and save the settings cookie
ooat.saveCookie = function() {
	
	// build an expiration date (10 years into the future)
	var exp = new Date();
	exp.setTime(exp.getTime() + (1000*60*60*24*365*10));
	
	// build the cookie with escaped JSON string and expiration date, and allow sharing between subdomains
	builtCookie = 'ooat_settings=' + escape(JSON.stringify(ooat.settings)) + '; expires=' + exp.toGMTString() + ';path=/;domain=.scottbradford.us';

	// set the cookie
	document.cookie = builtCookie;
};

// execute the function to save the cookie on script load
ooat.saveCookie();

// function to apply the current settings to the page
ooat.updateSettings = function() {
	
	// font size
	jQuery('body').css('font-size',(ooat.settings.fsz)+'px');
	jQuery('.entry').css('line-height',(ooat.settings.fsz+6)+'px');
	jQuery('#fontstat').html(ooat.settings.fsz+'px');

	// menu pin
	mbar = jQuery('.container.menu');
	if (ooat.settings.pin === false) {
		mbar.removeClass('pin');
		ooat.status.isMenuPinned = false;
	} else {
		//fixme
	}
	jQuery('#pinstat').html(ooat.settings.pin.toString());
};

ooat.erun = function(dest) {
	window.location = svr + dest + "/index.html"
}

// function to build the photo bars
ooat.photos.update = function() {
	var pos = '',
	    hold = 0,
	    len = jQuery('.pb').length;
	    
	ooat.photos[0] = (Math.floor(ooat.maximg*Math.random()))*(-320);
	pos = ooat.photos[0] + 'px 0px';
	
	jQuery('.sphotos .p0').css('backgroundPosition',pos);
	for (var i=1; i<len; i++) {
		hold = ooat.photos[i-1];
		while (jQuery.inArray(hold,ooat.photos) != -1) {
			hold=(Math.floor(ooat.maximg*Math.random())*(-320));
		}
		ooat.photos[i]=hold;
		pos =  ooat.photos[i] + 'px 0px';
		jQuery('.sphotos .p' + i).css('backgroundPosition',pos);
	}

	// fade all the photos and holiday stuff in after everything else is done
	jQuery('.sphotos').fadeIn('def');	
}

// function to perform the holiday ajax request (see functions.php)
// if we've already done it in this session (and haven't passed midnight), we don't bother donig it again
ooat.holiday.test = function() {
	var tempDate = new Date(),
	    currentMonth = tempDate.getMonth()+1,
	    currentDay = tempDate.getDate(),
	    holidayCookie = ooat.getJsonCookieByName('ooat_holiday');
	
	if (currentMonth < 10)
		currentMonth = '0'+currentMonth;
	if (currentDay < 10)
		currentDay = '0'+currentDay;
		
	var currentDate = currentMonth+'/'+currentDay;
	
	// only make the ajax request if there is no holiday session cookie, of if the date has changed since the cookie was set
	if ((typeof holidayCookie.isHoliday == 'undefined') || (holidayCookie.currentDate != currentDate)) {
		jQuery.ajax({
			type: 'POST',
			url: '/wp-admin/admin-ajax.php',
			data: {action:'ooat_test_holiday',date:currentDate,rand:ooat.rand()},
			dataType: 'json',
			error: function(err) {
				ooat.photos.update(false);
			},
			success: function(data) {
				
				// add the date from the request to the holiday session cookie
				data.currentDate = currentDate;
				
				// save the response to a session cookie
				document.cookie = 'ooat_holiday=' + escape(JSON.stringify(data));

				if (data.isHoliday) {
					ooat.holiday.show(data.holidayInfo)
				}
			}
		});
	} else {
	// if we have a valid holiday cookie set, just use the stored data
		if (holidayCookie.isHoliday) {
			ooat.holiday.show(holidayCookie.holidayInfo)
		}
	}
}

// function to reset all settings to defaults
ooat.resetSettings = function() {
	ooat.settings.fsz=12;
	ooat.settings.pin=true;
	ooat.settings.mob='none';
	ooat.settings.qcp=false;
	
	ooat.updateSettings();
	ooat.saveCookie();
}

// do all this stuff when the document is ready
jQuery(document).ready(function(){
	
	// hide the address bar in mobile browsers
	window.scrollTo(0,1);
	
	// ad an ad notification if there are Text Link Ads
	jQuery('span.textlinkad').prepend('<div class="adnote">Advertisement:</div>');
	
	// correct the pinned desktop menu positioning if there's a wpadminbar (WordPress 3.1+)
	if ((jQuery('#wpadminbar').length) > 0) {
		jQuery('.container.menu').addClass('ext');
		jQuery('.sbot').addClass('ext');
	}
	
	// run the holiday test function
	ooat.holiday.test();
	
	// launch the photobar
	ooat.photos.update();
	
	// make sure links are root-relative, rather than fully resolved, for local links (so we don't have unnecessary mobile redirection)
	// in other words, remove the http://www.scottbradford.us from URLs inside posts.
	jQuery('.entry .econtent a[href^="http://www.scottbradford.us"]').each(function(){
		jQuery(this).attr('href',(jQuery(this).attr('href').substr(27)));
	});
	
	// build listener for comment response expander
	jQuery("#showComment").click(function() {
		jQuery("div#respond").slideToggle('fast');
		return false;
	});
	
	// apply all site settings to the page
	ooat.updateSettings();
	
	// listener to handle showing/hiding settings panel
	jQuery('#showset').click(function(){
		jQuery('.swin').slideToggle('fast');
		return false;
	});

	// listener to handle increasing/reducing font sizes
	jQuery('#fontup,#fontdn').click(function(){
		if (this.id == 'fontup') {
			ooat.settings.fsz = ooat.settings.fsz+1;
		} else if (this.id == 'fontdn') {
			ooat.settings.fsz = ooat.settings.fsz-1;
		}
		ooat.updateSettings();
		ooat.saveCookie();
		return false;
	});
	
	// listener to handle menu pinning setting
	jQuery('#pintoggle').click(function(){
		if (ooat.settings.pin === false) {
			ooat.settings.pin = true;
		} else {
			ooat.settings.pin = false;
		}
		ooat.updateSettings();
		ooat.saveCookie();
		return false;
	});
	
	// listener to handle settings reset clicks
	jQuery('#resetsettings').click(function(){
		ooat.resetSettings();
		return false;
	})

});
