// Namespace function
function namespace(ns) {
    ns = ns.split('.');
    var cur = window, i;
    while ( i = ns.shift() ) {
        if ( !cur[i] ) cur[i] = {};
        cur = cur[i];
    }
}
// Put all tictoc functions into the tictoc object like:
// quartz.test = function() { alert("Test"); }
namespace("tictoc");


// Setup JS events when the DOM is ready
$(document).ready(function(){
	// CSS Style switcher
	//tictoc.style_switcher.setup("website_style");
	
	// Drop-down menu for IE
	if (document.all) $("#menu li").hoverClass ("sfHover");
	
	// Content area images
	$(".pagebody img[@align='left']").addClass("left");
	$(".pagebody img[@align='right']").addClass("right");
	
	// Checkout signin
	if ($("form#sign_in").length > 0) {
		$("#sign_in #password").click( function(){ $("#registered1").attr("checked",true); });
		$("#sign_in #password").keypress( function(){ $("#registered1").attr("checked",true); });
	}
	
	// Progress button
	$("fieldset.buttons input").click(
		function() {
			$("#checkout fieldset.buttons img").show();
			$("#checkout fieldset.buttons input").hide();
			$("#checkout fieldset.buttons a").hide();
		});
	
	// Navigation
	tictoc.website.menu();
	
	// Popup links
	$("a.popup").each(tictoc.website.popup);
	
	// Admin links
	$("a.adminedit").click(tictoc.admin.edit);
	
	if ($("#line_items input").length > 0) {
		$("#line_items input[@type=text]").change(tictoc.website.totals);
		$("#line_items input[@type=text]").blur(tictoc.website.totals);
		$("#line_items input[@type=image]").click(tictoc.website.totals);
		tictoc.website.totals();
	}
	
	// Hide Labels from particular fieldsets
	$("form.hide_labels").each(tictoc.website.hide_labels);
	
	// 3D Secure Form
	if ($("#secure_authentication").length > 0) tictoc.website.submit_secure_form();
});

$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};


// General website functions
tictoc.website = {
    menu_colour: 'site',
	section: '',
	subsections: [],
	subsection_links: [],
	costs: [],
	
	// Hide labels, set text to targets value
	hide_labels: function() {
		$(this).find("label").each(function() {
			$('#' + this.htmlFor).val(this.innerHTML);
			$(this).hide();
			$('#' + this.htmlFor).click(tictoc.website.clearbox);
		})
	},
	
    // Clear default text in an input box
    clearbox: function() {
        if (!this.default_value) this.default_value = this.value;
    
        if (this.value == '') {
            this.value = this.default_value;
        } else if (this.value == this.default_value) {
            this.value = '';
        }
    },
    
    // Jump to URL
    jump_to_url: function(url) {
        if (url == "") return false;
	    location.href = "/" + url;
    },
    
    // Popup link
    popup: function() {
        this.target = "_blank";
        this.title =  this.title ? this.title += ". " : "";
        this.title += "Link opens in a new window."
    },

	// Set page menu
	menu: function() {
		var url = "/flash/menu.swf?";
		var params = [];
		var h = 60;
		
		if (this.subsections.length > 0) {
			params.push("subsections="+this.subsections.join(","));
			params.push("links="+this.subsection_links.join(","));
			h = 160;
		}
		
		if (this.section != "") params.push("section="+this.section);
		if (this.menu_colour != "") params.push("body_id="+this.menu_colour);
		
		url += params.join("&");
		var height = this.subsections
		
		$("#menu").flash({src: url, width: 880, height: h, wmode:"transparent"}, {version: '8'});
	},
	
	totals: function() {
		var total = 0;
		var places = 0;
		
		$("#line_items input[@type=text]").each(function(i){
			var v = parseInt($(this).val());
			v = (v > -1) ? v : 0;
			// if (i == 0) {
			// 	places = v;
			// } else {
			// 	if (v > places) v = places;
			// }
			
			$(this).val(v);
			total += $(this).val() * tictoc.website.costs[i];
		});
		
		$("#total").html(total.currency(2));
		return true;
	},
	
	submit_secure_form: function() {
		$("#secure_authentication")[0].submit();
	}
	
};


// Admin functions
tictoc.admin = {
    popup_width: 675,
    popup_height: 650,
    
    edit: function() {
        var win = window.open(this.href, "_adminedit","height=" + tictoc.admin.popup_height + ",width=" + tictoc.admin.popup_width + ",resizable=yes,dependent,scrollbars=yes");
	    win.focus();
	    return false;
    }
};


// Style switcher functions 
// Based on: http://kelvinluck.com/assets/jquery/styleswitch/
// Add alternative stylesheets like:
// <link rel="alternate stylesheet" type="text/css" href="style2.css" title="style2" media="screen" />
// <link rel="alternate stylesheet" type="text/css" href="style1.css" title="style3" media="screen" />
tictoc.style_switcher = {
    // Default style cookie name
    cookie_name: "tictoc_style",
    
    // Setup style switcher
    setup: function(cookie_name) {
      if (cookie_name) this.cookie_name = cookie_name;
      var cookie = this.read_cookie(this.cookie_name);
	  if (cookie) this.switch_style(cookie);
	  
	  $(".styleswitch").click(function() {
		tictoc.style_switcher.switch_style($(this).attr("rel"));
		return false;
		});
    },
    
    // Switch stylesheet
    switch_style: function(name) {
	    $("link[@rel*=style]").each(function(i) {
    	    this.disabled = true;
    	    if ($(this).attr('title') == name) this.disabled = false;
    		});
    	this.create_cookie(name, 365);
    },
    
    // Create cookie
    create_cookie: function(value, days) {
        var expires, date;
	    if (days) {
    		date = new Date();
    		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    		expires = "; expires=" + date.toGMTString();
    	} else {
    	    expires = "";
    	}
    	document.cookie = this.cookie_name + "=" + value + expires + "; path=/";
    },
    
    // Read cookie
    read_cookie: function(name) {
	    var nameEQ = name + "=";
    	var ca = document.cookie.split(';');
    	
    	for (var i=0;i < ca.length;i++) {
    		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;
    },
    
    // Clear cookie
    clear_cookie: function() {
        this.create_cookie("", -1);
    }
};


// Extending the core functions
// Taken from: http://www.codeproject.com/jscript/prototypes.asp

// Reverse string
String.prototype.reverse = function() {
	return this.split('').reverse().join('');
	}

// String replicator
String.prototype.times = function(n) {
	var s = '';
	for (var i = 0; i < n; i++) s += this;
	return s;
	}

// Truncate number to n places
Number.prototype.truncate = function(n) {
	return Math.round(this * Math.pow(10, n)) / Math.pow(10,n);
	}

// Return fractional part
Number.prototype.fractional = function() {
	return parseFloat(this) - parseInt(this);
	}

// Group thousands
Number.prototype.group = function() {
	var s = parseInt(this).toString().reverse(), r = ''; 
	for (var i = 0; i < s.length; i++) r += (i > 0 && i % 3 == 0 ? ',' : '') + s.charAt(i);
	return r.reverse();
	}
	
// Zero-Trailing
String.prototype.zt = function(n) {
	return this + '0'.times(n - this.length);
	}

// Zero padding
String.prototype.zp = function(n) {
	return '0'.times(n - this.length) + this;
	}
Number.prototype.zp = function(n) {
	return this.toString().zp(n);
	}

// substr for numbers!
Number.prototype.substr = function(n) {
	return this.toString().substr(n);
	}

// format a number with n decimal digits and thousands separator
Number.prototype.currency = function(n) {
	// truncate and zero-trail the fractional part
	var f = this.fractional().truncate(n).substr(2).zt(n);

	// grouped integer part + dot + fractional part
	return this.group() + '.' + f;
	}
