// 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");
		
	// Content area images
	$(".pagebody img[@align='left']").addClass("left");
	$(".pagebody img[@align='right']").addClass("right");
	
	// Popup links
	$("a.popup").each(tictoc.website.popup);
	
	$("a#search_toggle").click(function(e) {
		tictoc.website.toggle_search_bar(e)
	});
	
	// Tap Variations
	if ($(".taps").length > 0 && $('#product_visuals').length > 0) {
		$('<img src="/images/loading_animation.gif" alt="Loading&hellip;" id="loading_animation" />').appendTo("#product_visuals").hide();
		$(".taps #variations li a").each(tictoc.website.setup_tap_image_swapper);
	}
		
	// Admin links
	$("a.adminedit").click(tictoc.admin.edit);
	
	// Product page heading colour match
	// if($("#product_intro .content span",".granite, .stainless, .ceramic, .undermounts, .sinks").length>0){
	// 	// alert('has span');
	// 	$("#product_intro h2").css({"color" : $("#product_intro .content span:last").css("color")});
	// }else if($("#product_intro .content h5:first",".granite, .stainless, .ceramic, .undermounts, .sinks").length>0){
	// 	// alert('has h5');
	// 	$("#product_intro h2").css({"color" : $("#product_intro .content h5:first").css("color")});
	// }else{
	// 	// alert('has other');
	// 	$("#product_intro h2").css({"color" : $("#product_intro .content p:last").css("color")});
	// }

});

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


// General website functions
tictoc.website = {
	setup_tap_image_swapper: function() {

		$(this).click(function(e) {
			e.preventDefault();
			if (this.className.indexOf("current") == -1) {
				// NOT the currently viewed tap
				var product_id = this.href.split("/")[this.href.split("/").length-1]
				var fetch_url = location.protocol + "//" + location.host + "/products/data/" + product_id + ".json"
				$('#loading_animation').show();
				
				var request_properties = {
					url: fetch_url,
					type: 'get',
					dataType: 'json',
					success: tictoc.website.set_current_tap,
					complete: function() { $('#loading_animation').hide(); }
					}
				
				$.ajax(request_properties)			
			}
		});
	},
	
	set_current_tap: function(payload) {
		if (payload) {
			$(".taps #variations li a").each(function() {
				var link_sku = this.href.split("/")[this.href.split("/").length-1];
				var current_id = payload.attributes['id'];
												
				if (link_sku.substring(0,(current_id + "").length) == current_id) {
					$(this).addClass('current');
				} else {
					$(this).removeClass('current');
				}
			});			
console.log(payload)
			$("#product_image")[0].src = location.protocol + "//" + location.host + "/documents/" + payload.attributes['document_id'] + "/" + payload.attributes['document_id'] + "-medium.png"		
		}
	},

	toggle_search_bar: function(e) {
		e.preventDefault();
		$("#search_bar").slideToggle("fast");
	},

    // 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."
    }
};


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