////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////GLOBAL VARIABLES
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var loggingEnabled = 0; //Enable the log console (press ` to view when enabled)... It is a good idea to tie this in with logic to enable when in staging / dev environments

//PrettyPhoto - gallery arrays
var images = ['/!GLOBAL/images/console/console01.jpg', '/!GLOBAL/images/console/console02.jpg', '/!GLOBAL/images/console/console03.jpg', '/!GLOBAL/images/console/console04.jpg', '/!GLOBAL/images/console/console05.jpg', '/!GLOBAL/images/console/console06.jpg', '/!GLOBAL/images/console/console07.jpg', '/!GLOBAL/images/console/console08.jpg', '/!GLOBAL/images/console/console09.jpg', '/!GLOBAL/images/console/console10.jpg', '/!GLOBAL/images/console/console11.jpg'];
var titles = ['Your dashboard provides quick glance information.', 'You can add, edit, delete and re-order pages easily.', 'Our content editor makes it easy to enter and edit content.', 'You can even edit or disable any page from the content libraries.', 'Posting and managing your blog posts is easy.', 'Uploading and managing files and photos is easy.', 'Appointment requests and online enquiries are recorded.', 'Newsletters can be edited before they are sent. You can post your own mailouts too.', 'Manage your website members or export them with ease.', 'Keep your practice details up-to-date.', 'Control which features are enabled on your website.'];
var descriptions = ['', '', '', '', '', '', '', '', '', '', ''];



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////DOM READY (jQ)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {

////Environment variables
	//Determine platform
	userOSAgent = navigator.userAgent.toLowerCase();
	$.platform = {
		mac: /mac/.test(userOSAgent),
		osx: /mac os x/.test(userOSAgent),
		win: /win/.test(userOSAgent),
		linux: /linux/.test(userOSAgent)
	};
	//Some IE7 reports version number as 6.0 The following line fixes this.
	$.browser.version = $.browser.msie && parseInt($.browser.version) == 6 && window["XMLHttpRequest"] ? "7.0" : $.browser.version;
	//get URL
	pageURL = window.location.href;


////Create the required DIV element at runtime
	//Log console
	if (loggingEnabled) $("<div id='logg'>DEBUG:<br></div>").appendTo("body"); $("<style type='text/css'>#logg{position:fixed;display:none;right:0;top:0;width:300px;height:150px;background-color:#DDD;overflow:scroll;text-align:left;}</style>").appendTo("head"); $(document).keypress( function(e) { if (e.which == 96) { $("#logg").toggle(); return false; } });


////Add the feedback button to page, as long as not IE6
	if ($.browser.msie && $.browser.version == 6) {
	} else {
		$("#footer").append("<div id='feedbackButton'><a href='http://physiopulse.wufoo.com/forms/we-value-your-feedback?iframe=true&width=690&height=400' rel='prettyPhoto' title=''><img src='/!GLOBAL/images/but_feedback.gif' alt=''></a></div>");
	}


////Home page hero tab clicks & switching handler
	$("#heroTabs li").click(function () {
		var sourceID = $(this).attr("id")
		var itemName = sourceID.substring(3,sourceID.length);
		$("#heroTabs li").removeClass("selected"); $(this).addClass("selected");
		$("#heroCanvas .canvas").addClass("hide"); $("#hero"+itemName).removeClass("hide");
	});
	

////Get last tweet
	$.getJSON("http://twitter.com/statuses/user_timeline/physiopulse.json?callback=?", function(data) {
		//logg(data[0].text);
		//logg($.link(data[0].text));
		$("#tweet").html($.link(data[0].text));
		$("#footer .twitter").fadeIn();
	});


////FAQ handler
	$("ul.faq li div").hide();
	$("ul.faq li span:first-child").click(function () {
		$(this).next().slideToggle("fast");
		$(this).toggleClass("selectedFAQ");
	});


////ToolTip handler
	$(".tipTrigger").tooltip({
		position:"bottom right",
		effect:'fade',
		fadeInSpeed:100,
		fadeOutSpeed:100,
		offset:[-32,20]
	}).dynamic();


////Handle Accordion controls
	$("#accordion").tabs("#accordion div.pane", {tabs:'h3', effect:'slide', initialIndex:0});


////Handle table row stuff
	//striping
	$(".autoTable tr:odd").addClass("stripe");
	//for every row that contains a td (i.e. th excluded)
	$(".autoTable tr:has(td):not(.description)").hover(
		function() {
			$(this).addClass("hilite");
		},
		function() {
			$(this).removeClass("hilite");
		}
	);


////Form validation stuff
	$("#newsletterForm, #questionForm, #enquiryForm, #domainForm, #demoForm").validator({ 
		position: 'top left', 
		offset: [-14, 25],
		message: '<div><em/></div>' // em element is the arrow
	});


////Handle Admin Console gallery launch
	$(".galleryLauncher").click(function () {
		$.prettyPhoto.open(images,titles,descriptions);
	});


////Initialise prettyPhoto
	$("a[rel^='prettyPhoto']").prettyPhoto({
		theme:'dark_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
		default_width:615,
		default_height:360,
		animationSpeed:"fast",
		allowresize:false
	});


////Website ownership calculator
	$("input.calculator").live('change', function() {
		if ($(this).val() == "") $(this).val("0");
		$(this).val(parseFloat(stripButNumber($(this).val(),true)));
		doSums();
	});
	doSums(); //on first page load


////handle template thumb selectors
//	$$('#templates label').each(function(label) {
//		label.addEvent('click', function() {
//			$$('#templates label').removeClass('checked');
//			label.addClass('checked');
//		});
//	});
//	//Highlight checked thumb selector on page load



});




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////MISCELLANEOUS FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////Debugging purposes only
function logg(text) {
	if ($("#logg").length > 0) { //ie if #logg exists
		$("#logg").append(text+"<br>");
		$("#logg").attr({ scrollTop:$("#logg").attr("scrollHeight") }); //Scroll to bottom
	} else { //Write to Firebug console - for debugging only
		if (typeof(console) != "undefined") if (typeof(console.log) != "undefined") console.log.apply(this, arguments);
	}
}


////Return only whole number from mixed string
function stripButNumber(strIn, keepDecimal) {
	var strOut = new String(strIn);
    if (!keepDecimal) { strOut = strOut.replace(/\.\d+$/, ''); } //Ignores decimals at end
    strOut = strOut.replace(/[^\d\.]/g, ''); //Only keeps digits and decimals
	//logg("StrippedNums: " + strOut);
    return strOut; 
}


////Calculate the website ownership costs
function doSums() {
	var hours = 0;
	var dollars = 0;
	var hoursMonth = 0;
	var dollarsMonth = 0;
	var hourlyRate = parseFloat($("input#hourlyRate").val());
	
	//Total up-front hours
	$("input.hours").each(function(n) {
		hours = hours + parseFloat($(this).val());
	});
	//Total up-front dollars
	$("input.dollars").each(function(n) {
		dollars = dollars + parseFloat($(this).val());
	});
	//Total monthly hours
	$("input.hoursMonth").each(function(n) {
		hoursMonth = hoursMonth + parseFloat($(this).val());
	});
	//Total monthly dollars
	$("input.dollarsMonth").each(function(n) {
		dollarsMonth = dollarsMonth + parseFloat($(this).val());
	});

	$("span.hourlyRate").html(formatMoney(""+hourlyRate));
	$("b.upfrontCosts").html(formatMoney(""+(hourlyRate*hours+dollars)));
	$("b.monthlyCosts").html(formatMoney(""+(hourlyRate*hoursMonth+dollarsMonth)));
}


//Convert to money formatted
//formatMoney("12!3e1e2.129") returns "$12,312"
//formatMoney("12!3e1e2.129",2) returns "$12,312.13"
function formatMoney(numString, decimals) {
	var n = stripButNumber(numString,1);
	var decimals = isNaN(decimals = Math.abs(decimals)) ? 0 : decimals;
	var d = ".";
	var t = ",";
	var s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(decimals)) + "";
	var j = (j = i.length) > 3 ? j % 3 : 0;
	return "$" + s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (decimals ? d + Math.abs(n - i).toFixed(decimals).slice(2) : "");
};




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////JQUERY PLUGINS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////Various tools to manipulate text, such as linkifying text
////http://github.com/jamescarr/jquery-text-tools
(function(){
	if(jQuery){
		jQuery.extend({
			link:function(text){
				return text.replace(/(href="|<a.*?>)?[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function($0, $1) {
					return $1 ? $0 : $0.link($0);
				});
			}
		});
		jQuery.fn.extend({
			'link':function(){
				this.html(jQuery.link(this.html()));
			}
		});
	}
})();