// 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");
	
	// Popup links
	$("a.popup").each(tictoc.website.popup);
	
	// Admin links
	$("a.adminedit").click(tictoc.admin.edit)
	
	// Embedded video links
  	tictoc.website.embed_videos();
	
	// Remove submit button from form
	//$("#search_form #search_field_submit").hide();
	//$("#search_form #search_field").focus(tictoc.website.clearbox);
	//$("#search_form #search_field").blur(tictoc.website.clearbox);

	// Checkout signin
	if ($("#sign_in")) {
		$("#password").click(tictoc.website.registered_user);
		$("#password").keypress(tictoc.website.registered_user);
	}
	
	// Payment page
	if ($("#copy_address").length > 0) tictoc.website.copy_address();
    if ($("#place_order").length > 0) tictoc.website.place_order();

	// Hide Labels from particular fieldsets
	$("form.hide_labels").each(tictoc.website.hide_labels);	
	
	// Home news
	if ($(".tag_btn")) {
		$(".tag_btn").click(tictoc.website.news);
	}
	
	// Homepage banner animation
	if ($("#banners").length > 0) $.slideshow('banners', 4500);
	
	// 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); }
		);
	});
};


// jQuery fader
// Based on: http://portfolio.gizone.co.uk/applications/slideshow/
$.slideshow = function (containerId, timeout) {
	var current = 0;
	var id = '#' + containerId;
	$(id).css({position:'relative'});
	var slides = $(id).children().get();
	for ( var i = 0; i < slides.length; i++ ) {
		$(slides[i]).css({zIndex:(slides.length - i), position:'absolute', top:'9px', left:'9px'});
	}
	setTimeout((function(){$.slideshow.next(slides, timeout, current);}), timeout);
}
$.slideshow.next = function (slides, timeout, current) {
	for (var i = 0; i < slides.length; i++) {
		var slide = slides[(current + i) % slides.length];
		$(slide).css({zIndex:(slides.length - i)});
	}
	// IE doesn't seem to support .show() after it has been faded out, so we use .fadeIn("fast")
	$(slides[current]).fadeOut('slow', 
			function(){$(slide).css({zIndex:'0', opacity:1}).fadeIn("fast");}
			);
	
	current = (current + 1) % slides.length;
	setTimeout((function(){$.slideshow.next(slides, timeout, current);}), timeout);
};

// General website functions
tictoc.website = {
  
	// Hide labels, set text to targets value
	hide_labels: function() {
		$(this).find("label").each(function() {
			$('#' + this.htmlFor).val(this.innerHTML);
			$(this).hide();
			$('#' + this.htmlFor).focus(tictoc.website.clearbox);
			$('#' + this.htmlFor).blur(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;
			this.select();
        } 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."
    },

	change_image: function(id)	{
		$("#product_image img").each(function(i){
			if (this.id == id){
				$(this).show();
				$("#"+this.id+"t").addClass("active");
			} else {
				$(this).hide();
				$("#"+this.id+"t").removeClass("active");
			}
		});
		return false;
	},
	
	// Events for delivery address copying
	copy_address: function() {
	    $("#copy_address")[0].style.visibility = "visible";
		$("#copy_address_chk")[0].checked = false;
		$("#copy_address_chk").click( tictoc.website.copy_delivery );
		$("#delivery_address input").keyup( 
		    function(){
		        if ($("#copy_address_chk")[0].checked == true) tictoc.website.copy_delivery();
		        }
		    );
	    $("#billing_address input[type='text']").change( 
	        function(){ $("#copy_address_chk")[0].checked = false;} );
	},

	// Copy delivery address
	copy_delivery: function() { 
	    $("#order_billing_first_name").val($("#order_delivery_first_name").val());
	    $("#order_billing_last_name").val($("#order_delivery_last_name").val());
	    $("#order_billing_address1").val($("#order_delivery_address1").val());
	    $("#order_billing_address2").val($("#order_delivery_address2").val());
	    $("#order_billing_city").val($("#order_delivery_city").val());
	    $("#order_billing_county").val($("#order_delivery_county").val());
	    $("#order_billing_postcode").val($("#order_delivery_postcode").val());
	},
	
	// Place order
    place_order: function() {
        $("#place_order p")[0].style.display = "none";
        $("#place_order input").click( 
            function(){ 
                $("#place_order input")[0].style.display = "none";
                $("#place_order img")[0].style.display = "inline";
                return true;
            });
    },
	
	// Sign up form
	registered_user: function() {
		$("#registered1").attr("checked",true); 
	},
	
	submit_secure_form: function() {
		$("#secure_authentication")[0].submit();
	},
	
	// Newsletter signup
    news: function()
    { 
        $.ajax({
            type: "POST",
            url: "/home_news",  
            dataType: "html",
            data: "tag=" + this.id,
            success: function(data){
                // Returned data would be html of options list
                $("#ajax_news").html(data);
				// Home news
				if ($(".tag_btn")) {
					$(".tag_btn").click(tictoc.website.news);
				}
            }
        });
        return false;
    }, 
  
  embed_videos: function() {
    $('#content a[href*="youtube.com"]').flash(
      { width: 425, height: 350, wmode: 'transparent' },
      { version: 8 },
      function(htmlOptions) {
        htmlOptions.src = "http://www.youtube.com/v/" + this.href.match(/v=(.+)/)[1];
        $(this).before($.fn.flash.transform(htmlOptions));
        $(this).remove();
      }
    );

    $('#body a[href*="vimeo.com"]').not($('#replies a')).flash(
      { width: 453, height: 340, quality:'best', allowfullscreen:'true', scale:'showAll' },
      { version: 8 },
      function(htmlOptions) {
        htmlOptions.src = "http://vimeo.com/moogaloop.swf?clip_id=" + this.href.match(/(\d+)/)[1] + "&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=FFCF4C";
        $(this).before($.fn.flash.transform(htmlOptions));
        $(this).remove();
      }
    );
  }
};


// 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);
    }
};
