// Variable declarations
var autoTimers=new Array();


/*
 * Date Format 1.2.3
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}
		
		//alert(date);

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		//alert(date);
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};



/*
 * End Date Format
 */


// Converts XML standard date format into local time, the passed in date is assumed to be UTC, must pass in a date format (see date.format.js)
function convertUTCtoLocal(inputDate,conversionFormat,returnType){
	// Get the local time
	var localDate = new Date();
	
	// Work out (in min) what the time offset is to UTC
	offset = localDate.getTimezoneOffset();
	
	//alert(jQuery.browser);
	
	wasMozilla = "";
	
	jQuery.each(jQuery.browser, function(i, val) {
		if (i == "mozilla"){
			wasMozilla = "yes";
		}
	});
	
	if (wasMozilla == "yes") {
		inputDate = inputDate;
	} else {
		inputDate = inputDate.replace(/-/gi,"/");
	}
	
	
	//alert(inputDate);
	
	// Turn the date into milliseconds, then add the offset to it
	newDate = Date.parse(inputDate) - (offset *60 * 1000);
	//alert(inputDate);
	//alert(Date.parse(inputDate));
	
	// Convert the milliseconds back into a standard date
	veryNewDate = new Date(newDate);
	
	// convert the date into the specified format
	finalDate = dateFormat(veryNewDate, conversionFormat);
	
	// return the formatted date
	return finalDate;
	
}


// Function currently does not work in IE6
function processDate() {
	// Reformats the standard date field that PHP spits out by default
	$('.date').each(function(){
						 
		// check for the standard 0 date from PHP, if not this fails horribly and takes the rest of the JS with it!
		if ($(this).text() != "0000-00-00 00:00:00" && $(this).text() != "") {
			
			// Get the date
			dateToPass = $(this).text();
			
			
			// Need to add the T in for mozilla browsers
			jQuery.each(jQuery.browser, function(i, val) {
				if (i == "mozilla"){
					dateToPass = dateToPass.replace(' ','T');
				}
			
			});
			
			// Get the conversion format (from the 'rel' attribute)
			conversionFormat = $(this).attr('rel');
			
			// Convert the time from UTC (stored in db) to local time (regardless of where you are!), pass in the conversion format for good measure
			// this function stops the JS working in chrome (and safari!)
			finalDateFormat = convertUTCtoLocal(dateToPass,conversionFormat);
			
			// We'll do a quick convert of the rev format to the title tag before we finish....
			$(this).attr('title',convertUTCtoLocal(dateToPass,$(this).attr('rev')));
			
			// Then throw it back into the place where you got it from
			$(this).text(finalDateFormat);
			
		} else {
			
			// If the date is set to 0, or does not exist, simply pass this message back into the page
			$(this).text("-- No date --");
		}
		
	});
}





// Function preps links in targeted div's pagination
function paginationAjax(targetDiv) {
	
	// Set an onclick event for the links
	$('.' + targetDiv + ' .pagination a').click(function(ev){
														 
		// stop them from actually taking you to the page
		ev.preventDefault();
		
		// Then run the ajax call
		ajaxCall($(this).attr('href'),targetDiv);
	});	
}



// Function preps links in targeted div's pagination
function paginationAjaxAuto(targetDiv) {
	
	// Set up the links
	paginationAjax(targetDiv);
	
	// Set an onclick event for the links
	$('.' + targetDiv + ' .autopagination .autonext a').each(function(){
		
		// Then run the ajax call
		timerValue = $('.' + targetDiv + ' .autopagination .autotimer').text() + "000";

		// Set the interval timer 
		autoTimers[targetDiv] = setInterval("ajaxCall($('." + targetDiv + " .autopagination .autonext a').attr('href'),'" + targetDiv + "')",timerValue);

	});	
}


// Ajax call for pagination
function ajaxCall(pageUrl,targetDiv) {
	
	// Do the ajax
	$.ajax({
		// Use the passed in url
		url: pageUrl,   
		success: function(html) {
			// Chance the target div's content
			$('.' + targetDiv).html(html);
			
			//re-bind the links that have just been written in
			paginationAjax(targetDiv);
			
			// And re-run what needs to be re-run
			reRunableFunctions();
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			
			// Might want to change this to a more appropriate error message
			alert('something went wrong');
		}
	});	
}

function ajaxSubmit(submitTo,dataString,returnMessageElement) {
	$.ajax({
		type: "POST",
		url: submitTo,  
		data: dataString,  
		success: function(html) {
			
			// Insert the returned information after the specified
			$(returnMessageElement).append(html);
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			
			// if the ajax request fails
			$(returnMessageElement).append('<p class="error">Error</p>');
			
		}
	});
}



// Only run once
function startTheAjaxPagination() {

	$('.ajaxpage').each(function(){
		  
		var randomName = Math.round(Math.random() * 100000);
		$(this).addClass('rp' + randomName);
		
		if ($(this).find('.autotimerenable').text() == 1) {
			paginationAjaxAuto('rp' + randomName);
		} else {
			paginationAjax('rp' + randomName);
		}
		
	});
	
}


// Setting up twitter related content
function tweetLinking() {
	
	// Default twitter search address
	var test = "http://twitter.com/search?q=%23";
	
	// Loop around the content
	$('.tweetformat').each(function(){
		
		// Check to see if this content has already been parsed
		if ($(this).hasClass('fixed') == false) {
			
			// Scan the content and add in the appropriate twitter links (i.e. '#' and '@' links)
			$(this).html($(this).html().replace(/#(.*?)(\s|$)/g,'<a class="hash" href="$1">#$1 </a>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,'<a href="$&">$&</a> ').replace(/@(.*?)(\s|\(|\)|$)/g,'<a href="http://twitter.com/$1">@$1 </a>$2'));
			
			// To better deal with the has tags, use the twitter search address above and then use it in the link
			$(this).find('.hash').each(function(){
				$(this).attr('href',test + $(this).attr('href'));
			});
			
			// Finnaly add a fixed class to stop the function re-running on itself.
			$(this).addClass('fixed');
			
		}
	});
}


// Spoofing links to make the page easier to use for visitors
function makelink() {
	
	// Unbind all first
	$('.makelink').unbind();
	
	// Then make them clickable
	$('.makelink').click(function(){
								  
		// Just changing the location to the next link inside the div clicked
		window.location = $(this).find('a:first').attr('href');
		
	});
}






// Sets up the submition for the comments form
function submitCommentPrimer() {
	
	// Set up the click function
	$('.form-submit').click(function(){
		
		// Error message for failing the validation
		errorMessage = 'Please complete all required fields.';
		
		// Do the content check (at the moment, checks to see if the content is empty or now)
		if (commentFormValidation(errorMessage) == true) {
		
			// Set up the data variables
			var post_id = 'post_id=' + $('#comment_post_id').val();
			var comment_name = 'comment_name=' + encodeURIComponent($('#comment_name').val());
			var comment_email = 'comment_email=' + encodeURIComponent($('#comment_email').val());
			var comment_content = 'comment_content=' + encodeURIComponent($('#comment_content').val());
			var submitTo = "/comment_submit.html";
			var dataString = post_id + "&" + comment_name + "&" + comment_email + "&" + comment_content;
			
			// do the Ajax request
			$.ajax({
				type: "POST",
				url: submitTo,  
				data: dataString,  
				success: function(html) {
					
					// Insert the returned information after the comment form
					$('#post-comment').append(html);
					
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					
					// if the ajax request fails
					$('#post-comment').append('<p class="error">Error</p>');
					
				}
			});
		
		}
		
	});
	
}

function formSetup() {
	
	$('.submit-form').each(function() {

		thisForm = $(this);

		$(this).find('.submit').click(function(){
			
			if (formValidation($(this).parents('.submit-form').attr('id'),"Please fill in all required fields","") == true) {
				$('<span class="pass">Winner</span>').insertAfter(this);
				
				// Do ajax submition
				
				submitTo = $(this).parents('.submit-form').attr('action');
				dataString = "";
				i = 0;
				returnMessageElement = '#' + $(this).parents('.submit-form').attr('id');

				$(this).parents('.submit-form').find('input,textarea').each(function() {
					
					if (i = 0) {
						dataString = "submit_" + $(this).attr('id') + "=" + $(this).val();
					} else {
						dataString = dataString + "&" + "submit_" + $(this).attr('id') + "=" + $(this).val();
					}

				});
				
				ajaxSubmit(submitTo,dataString,returnMessageElement);
				
			}
			
		});
		
	});
	
}

// returns true if it passes
function emailValidation(value) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

// Form content checker, still has some comment specific things in it, but is now fairly generic
function commentFormValidation(errorMessage) {
	
	// Set up the counters
	var pass = 0;
	var counter = 0;
	
	// Remove any other error message this function may have created before
	$('.comment-error-message').remove();
	
	// For each input and text area with the "required" class, we need to check
	$('input.required,textarea.required').each(function(){
		
		// Increment the counter
		counter++;
		$('.comment-specific-error-message').remove();
		
		// Check to see if it's empty or not
		if ($(this).val() != "") {
			
			if ($(this).hasClass('email')) {
				if (emailValidation($(this).val())) {
					// Remove the error class if was ever added before
					$(this).removeClass('error');
					// Increment the pass counter
					pass++;	
				} else {
					$(this).addClass('error');
				}
			} else {
				
				if ($(this).hasClass('length')) {
					
					if ($(this).val().length < 300) {
						// Remove the error class if was ever added before
						$(this).removeClass('error');
						// Increment the pass counter
						pass++;	
					} else {
						$(this).addClass('error');
						$('<span class="comment-specific-error-message error">Too many characters, limit is 300</span>').insertAfter(this);
					}
					
				} else {
					// Remove the error class if was ever added before
					$(this).removeClass('error');
					// Increment the pass counter
					pass++;	
				}
			}
		} else {
			// Highlight the element with the 'error' class
			$(this).addClass('error');
		}
		
	});
	
	// Did everything pass?
	if (pass == counter) {
		
		// If they did, submit it
		return true;
	} else {
		
		// Otherwise, add the error message just after the submit button
		$('<span class="comment-error-message error">' + errorMessage + '</span>').insertAfter('.form-submit');
		
		// And return false to be safe
		return false;
	}
	
}


function formValidation(formId,errorMessage,errorPosition) {
	
	// Set up the counters
	var pass = 0;
	var counter = 0;
	
	// Remove any other error message this function may have created before
	$('#' + formId).find('.error-message').remove();
	
	// For each input and text area with the "required" class, we need to check
	$('#' + formId).find('input.required,textarea.required').each(function(){
		
		// Increment the counter
		counter++;
		
		// Check to see if it's empty or not
		if ($(this).val() != "") {
			// Remove the error class if was ever added before
			$(this).removeClass('error');
			// Increment the pass counter
			pass++;	
		} else {
			// Highlight the element with the 'error' class
			$(this).addClass('error');
		}
		
	});
	
	// Did everything pass?
	if (pass == counter) {
		
		// If they did, submit it
		return true;
	} else {
		
		// Otherwise, add the error message just after the submit button
		if (errorPosition == '') {
			$('<span class="error-message error">' + errorMessage + '</span>').insertAfter($('#' + formId).find('.submit'));
		} else {
			$('<span class="error-message error">' + errorMessage + '</span>').insertAfter('#' + errorPosition);
		}
		
		// And return false to be safe
		return false;
	}
	
}

/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/

// Just grouping functions that need to be re-run at the same time, if more are needed stick them in here later
function reRunableFunctions() {
	
	// Run the twitter content link adder
	tweetLinking();
	
	// Make divs that need to be links!
	makelink();
	
}



// On Page Load (ready)
$(document).ready(function() { 
	
	// Start the pagination function
	startTheAjaxPagination();
	
	// Run the other functions that need to
	reRunableFunctions();
	
	// Set up the comments submitter
	submitCommentPrimer();
	
	// Convert dates from UTC to local
	processDate();
	
	
}); 
