// Process!

//1. shirt_builder.init();
	// Sets the image builder up with an API instance, and generally makes things ready.
//2. shirt_builder.set_dynamic_text( ... );
	// See the function definition for data passed.  This sets the dynamic part of the shirt template so that you can build the shirt via the API.
//3. shirt_builder.build_spreadshirt_product();
	// Builds a spreadshirt object around the existing template with the dynamic text set in step 2
//4. shirt_builder.get_product_image_url();
	// Returns the URL for an image of the product as it exists in Spreadshirt's system.  Currently hardcoded at 450x450 pixels, but could be changed in this function
//5. shirt_builder.build_checkout_url();
	// This commamd truncates a series of steps.  It creates a new Spreadshirt basket, adds the product from step 3 to that basket, gets the checkout URL from Spreadshirt for that basket, and then signs that URL using Janrain authentication in order to pre-populate user data on that basket.
//6. shirt_builder.get_checkout_url();
	// Returns the URL string for the signed cart.  Send the user to this URL to check them out.


var shirt_builder = {
	checkout_url : "",
	shop_id : 366628,
	platform : "live", // Use "dev" for dev environment, or "live" for live API calls
	img_width : '250',
	img_height : '250',
	product_id : "",
	product : {
		type_id : "722", // Men's standard weight t-shirt
		//type_id : "210",
		appearance_id : "478", // Red
		//appearance_id : "196",
		size_id : "4", // Default to size L.  Values are: S=2, M=3, L=4, XL=5, XXL=6
		quantity : "1", // Default to just one shirt.
		configurations : [
			{
				type : "text", // Either "text" or "design"
				print_area_id : "1524", // "330" is a 331mmx587mm rectangle
				//print_area_id :	"330",
				print_type_id : "14", // Ditto
				offset : {
					x : "150", // X coordinate offset (in mm) from the top left of the print area
					y : "100" // Y coordinate offset (in mm) from the top left of the print area
				},
				content : {
					svg : {
						text : {
							transform : "rotate(350)",
							font_style : "normal",
							font_size : "56",
							font_weight : "normal",
							font_family : "CooperBlackLTRegular",
							text_anchor : "middle", // use "middle" to anchor from the middle of the SVG definition
									// The anchor is the point on the SVG itself, that is positioned per your X,Y coordinates
							printColorId : "12",
							tspans : [
								{
									x : "",
									y : "",
									text : "I'm a"
								}
							]
						}
					}
				},

				restrictions : {
					changeable : "false" // Whether or not the product design can be modified after creation
				}
			},

			{
				type : "design", // Either "text" or "desgin"
				print_area_id : "1524", // "330" is a 331mmx587mm rectangle
				//print_area_id :	"330",
				print_type_id : "14", // Ditto
				offset : {
					x : "150", // X coordinate offset from the top left of the print area
					y : "170" // Y coordinate offset from the top left of the print area
				},
				content : {
					svg : {
						image : {
							transform : "",
							height : "83.3966666667",
							width : "136.101666667",
							printColorIds : "12",
							designId : "11722925"
						}
					}
				},
				restrictions : [
					{
						"name" : "changeable",
						"value" : "false" // Whether or not the product design can be modified after creation
					}
				]

			}
		]
	},
	api : "", // The spreadshirt API instance will be stored here.
	
	init : function(shop_id, platform){
		if(shop_id)
			this.shop_id = shop_id;
		if(platform)
			this.platform = platform;
		this.api = new SpreadshirtAPI(this.platform, this.shop_id, true);
		return this;
	},

	set_dynamic_text : function(text, font_size, startx, starty){
		// @text: an array of strings, each representing one line of text
		// @font_size: the point size of the font
		// @x: the base X coordinate for this text block
		// @y: the base Y coordinate for this text block
		var svg_definition = {
			type : "text", // Either "text" or "design"
			print_area_id : "1524", // "330" is a 331mmx587mm rectangle
			//print_area_id :	"330",
			print_type_id : "14", // Ditto
			offset : {
				x : startx, // X coordinate offset (in mm) from the top left of the print area
				y : starty // Y coordinate offset (in mm) from the top left of the print area
			},
			content : {
				svg : {
					text : {
						transform : "rotate(350)",
						font_style : "normal",
						font_size : (font_size) ? font_size : "56",
						font_weight : "normal",
						font_family : "CooperBlackLTRegular",
						text_anchor : "middle", // use "middle" to anchor from the middle of the SVG definition
								// The anchor is the point on the SVG itself, that is positioned per your X,Y coordinates
						printColorId : "12",
						tspans : [
						]
					}
				}
			},
			restrictions : {
				changeable : "false" // Whether or not the product design can be modified after creation
			}
		};
		if (text[1]!='') {
			this.product.configurations[1].offset.y = 200
		}
		for(var i = 0; i < text.length; i++){
			svg_definition.content.svg.text.tspans.push({
				// Y is straight-forward, calculate heigh difference based on line height with 20% padding
				y : (font_size * i),
				// X is calculated using trigonmotry.  Solve X position based on length of Y and the Law of Sines.  Then divide by 3.5 to make it fit?  (Not sure why that's necessary...  Possibly because X and Y are in mm and font is in points?)
				x : Math.sin(Math.PI / 180 * 10) * (font_size * i) / Math.sin(Math.PI / 180 * 80) / 3.5,
				text : text[i]
			});
		}
		       
		
		this.product.configurations[2] = svg_definition;// The first two items in configurations are the "I'm a" text and the logo.  So [2] is ALWAYS the dynamic text for our purposes

	},

	get_product_xml : function(){
		var xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
		xml += '<product xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">';
		xml += '<productType id="'+this.product.type_id+'"/>';
		xml += '<appearance id="'+this.product.appearance_id+'"/>';
		xml += '<configurations>';
		for(var i = 0; i < this.product.configurations.length; i++){
			xml += '<configuration type="'+this.product.configurations[i].type+'">';
			xml += '<printArea id="'+this.product.configurations[i].print_area_id+'"/>';
			xml += '<printType id="'+this.product.configurations[i].print_type_id+'"/>';
			xml += '<offset unit="mm"><x>'+this.product.configurations[i].offset.x+'</x><y>'+this.product.configurations[i].offset.y+'</y></offset>';
			xml += '<content dpi="25.4" unit="mm">';
			xml += '<svg>';
			if(this.product.configurations[i].type == "design"){
				xml += '<image transform="'+this.product.configurations[i].content.svg.image.transform+'" '+
					'height="'+this.product.configurations[i].content.svg.image.height+'" '+
					'width="'+this.product.configurations[i].content.svg.image.width+'" '+
					'printColorIds="'+this.product.configurations[i].content.svg.image.printColorIds+'" '+
					'designId="'+this.product.configurations[i].content.svg.image.designId+'" '+
					'/>';
			}
			else if(this.product.configurations[i].type == "text"){
				xml += '<text transform="'+this.product.configurations[i].content.svg.text.transform+'" '+
					'font-style="'+this.product.configurations[i].content.svg.text.font_style+'" '+
					'font-size="'+this.product.configurations[i].content.svg.text.font_size+'" '+
					'font-weight="'+this.product.configurations[i].content.svg.text.font_weight+'" '+
					'font-family="'+this.product.configurations[i].content.svg.text.font_family+'" '+
					'text-anchor="'+this.product.configurations[i].content.svg.text.text_anchor+'" '+
					'printColorId="'+this.product.configurations[i].content.svg.text.printColorId+'">';
				for(var j = 0; j < this.product.configurations[i].content.svg.text.tspans.length; j++){
					xml += '<tspan';
					if(this.product.configurations[i].content.svg.text.tspans[j].x)
						xml += ' x="'+this.product.configurations[i].content.svg.text.tspans[j].x+'"';
					if(this.product.configurations[i].content.svg.text.tspans[j].y)
						xml += ' y="'+this.product.configurations[i].content.svg.text.tspans[j].y+'"';
					xml += '>'+this.product.configurations[i].content.svg.text.tspans[j].text+'</tspan>';
				}
				xml += '</text>';
			}
			xml += '</svg>';
			xml += '</content>';
			xml += '<restrictions>';
			for(var j = 0; j < this.product.configurations[i].restrictions.length; j++){
				xml += '<'+this.product.configurations[i].restrictions[j].name+'>'+
					this.product.configurations[i].restrictions[j].value+'</'+
					this.product.configurations[i].restrictions[j].name+'>';
			}
			xml += '</restrictions>';
			xml += '</configuration>';
		}
		xml += '</configurations>';
		xml += '</product>';
		return xml;
	},

	get_basket_xml : function(){
		var xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
		xml += '<basket xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">';
		xml += '<shop id="'+this.shop_id+'"/>';
		xml += '</basket>';
		return xml;
	},

	get_basket_item_xml : function(){
		var xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
		xml += '<basketItem xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">';
		xml += '<shop id="'+this.shop_id+'"/>';
		xml += '<quantity>'+this.product.quantity+'</quantity>';
		xml += '<element id="'+this.product_id+'" type="sprd:product" xlink:href="http://api.spreadshirt.com/api/v1/shops/'+this.shop_id+'/products/'+this.product_id+'">';
		xml += '<properties>';
		xml += '<property key="appearance">'+this.product.appearance_id+'</property>';
		xml += '<property key="size">'+this.product.size_id+'</property>'; // Default to size L.  Values are: S=2, M=3, L=4, XL=5, XXL=6
		xml += '</properties>';
		xml += '</element>';
		xml += '</basketItem>';
		return xml;
	},

	build_spreadshirt_product : function(){
		var product_url = this.api.createProduct(this.get_product_xml());
		this.product_id = product_url.replace(/^.*\/(\d+)$/, "$1");
		return this;
	},

	get_product_image_url : function(){
		var image_domain = 'image.spreadshirt.com';
		if (this.platform == 'dev') {
			image_domain = 'image.atbhn.de';
		}
		if(this.product_id)
			return "http://"+image_domain+"/image-server/v1/products/"+this.product_id+"/views/1,mediaType=png,width="+this.img_width+",height="+this.img_height+"";
		else
			return "ERROR: product_id not set";
	},

	get_checkout_url : function(){
		if(this.checkout_url)
			return this.checkout_url;
		else
			return "ERROR: checkout_url not set";
	},

	set_size : function(size){
		if(size.toUpperCase() == "S")
			size = 2;
		else if(size.toUpperCase() == "M")
			size = 3;
		else if(size.toUpperCase() == "L")
			size = 4;
		else if(size.toUpperCase() == "XL")
			size = 5;
		else if(size.toUpperCase() == "XXL")
			size = 6;
		this.product.size_id = size;
		return this;
	},

	set_quantity : function(quantity){
		this.product.quantity = quantity;
	},

	open_shop_frame : function(){
		var base_basket_url = this.api.createBasket(this.get_basket_xml());
		this.api.createBasketItem(base_basket_url, this.get_basket_item_xml());
		var base_checkout_url = this.api.checkout(base_basket_url);
		var checkout_url = '';
		$.ajax({
			type: "GET",
			async: true,
			cache: false,
			url: '/promotions/aooak/sign_basket.php?base_url=' + encodeURIComponent(base_checkout_url),
			success: function(data) { 
				var userAgent = navigator.userAgent.toLowerCase(); 
				$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 

				// Is this a version of Chrome?
				if($.browser.chrome){
				  userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
				  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
				  $.browser.version = userAgent;
				  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
				  $.browser.safari = false;
				}

				// Is this a version of Safari?
				if($.browser.safari){
				  userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);
				  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
				  $.browser.version = userAgent;
				}

                //update the shirt link for safari, see profile_home.php
				if ($.browser.safari && !$.browser.chrome) {
                    $('#getShirtLink').attr('href', data);
				}else {
					$('#overlay_content').html("<div id='buy_shirt' class='overlay_purchase'><a class='close' href='#' onclick='aooak.close_overlay(); return false;'>close</a><iframe src='/promotions/aooak/spreadshirt_redirect/?url="+data+"' width='100%' height='100%'></iframe></div>");
				}
		    	checkout_url = data;
			}
		});
		this.checkout_url = checkout_url;
		return this;
	},
	build_checkout_url : function(){
		var base_basket_url = this.api.createBasket(this.get_basket_xml());
		this.api.createBasketItem(base_basket_url, this.get_basket_item_xml());
		var base_checkout_url = this.api.checkout(base_basket_url);
		var data = $.ajax({
			type: "GET",
			async: false,
			cache: true,
			url: '/promotions/aooak/sign_basket.php?base_url=' + encodeURIComponent(base_checkout_url)
		});
		this.checkout_url = data.responseText;
		return this;
	}
}

