/*
Copyright (c) 2006-2009 EXTROMEDIA
All rights reserved.
Version 0.1.1

Robert J. Pope
EXTROMEDIA - Open Source Software & E-Business Solutions
200 E. Big Beaver Rd.
Troy, Michigan
48083 USA
Toll-Free: 1-800-643-2010
*/

var Verticart = {
	Version: "0.1.1",
	require: function(libraryName) {
		// inserting via DOM fails in Safari 2.0, so brute force approach
		document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
	}
};

function $() {
	var elements = [];
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string'){
			element = document.getElementById(element);
		}
		if (arguments.length == 1){
			return element;
		}
		elements.push(element);
	}
	return elements;
}


function set_cookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays===null) ? "" : ";expires="+exdate);
}

function get_cookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) {
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return null;
}

function removeChildren(element){
	if(element)
	{
		while( element.firstChild )
		{
			element.removeChild( element.firstChild );
		}
	}	
}


function render() {
	var name = $('name').value;
	name = name.replace('+','%2B');
	name = name.replace('&','%26');
	//alert(name);
	var url = '/create-a-shirt/engine.php';
	var pars = 'name=' + name + '&product='+$('product').value+'&design='+$('design').value+'&color='+$('color').value+'&text_color='+$('text_color').value+'&font='+$('font').value;
	var connection = YAHOO.util.Connect.asyncRequest('POST',url,render_callback,pars);
	$('config').style.display = 'block';
	$('output').style.display = 'block';
	var status_message = document.createElement('H1');
	status_message.appendChild( document.createTextNode('Loading...') );
	status_message.style.position = 'absolute';
	status_message.style.top = '200px';
	status_message.style.left = '280px';
	removeChildren( $('output') );
	$('output').appendChild( status_message );
	return false; //set to false if you want to disable the links or forms from going to their destination
}

function update_output(rendering) {
	var output = document.createElement('IMG');
	output.src = rendering.responseText;
	removeChildren( $('output') );
	$('output').appendChild( output );

	/*	
	var buy_button = document.createElement('A');
	buy_button.appendChild( document.createTextNode('ORDER') );
	buy_button.onclick = function() { Verticart.cart.update(); };
	buy_button.style.position = 'absolute';
	buy_button.style.left = '585px';
	buy_button.style.top = '10px';
	buy_button.style.width = '40px';
	buy_button.href = '#buy';
	buy_button.setAttribute('class','button');
	$('output').appendChild( buy_button );
	*/
	
	/*
	var back_button = document.createElement('A');
	back_button.appendChild( document.createTextNode('CLOSE') );
	back_button.style.position = 'absolute';
	back_button.style.right = '10px';
	back_button.style.top = '10px';
	back_button.style.width = '40px';
	back_button.href = '#back';
	back_button.setAttribute('class','button');
	back_button.onclick = function() { 
		$('output').style.display = 'none';
		$('config').style.display = 'block';
	};
	$('output').appendChild( back_button );
	*/
	
	$('config').style.display = 'block';
	$('output').style.display = 'block';
	
	/*alert(rendering.responseText);*/
}



function update_product() {
	/* PRODUCT_LIST */
	removeChildren( $('color') );

	
	if($('product')){
		var product = $('product').value;
		if(Verticart.catalog.products[product]){
			for(i in Verticart.catalog.products[product].attributes.colors){
				if(i){
					/*
					n = document.createElement('IMG');
					n.setAttribute('id',i);
					thumbnail = Verticart.catalog.products[product].attributes.colors[i].thumbnail;
					n.setAttribute('src','/create-a-shirt/products/'+product+'/thumbnails/'+thumbnail);
					//n.setAttribute('src','/create-a-shirt/products/'+product+'/thumbnails/'+eval("Verticart.catalog.products['"+product+"'].attributes.colors."+i+".thumbnail"));
					*/
					n = document.createElement('OPTION');
					n.setAttribute('value',i);
					//n.setAttribute('style',"background-repeat: no-repeat; background-position: center; background-image: url('/create-a-shirt/products/"+product+"/"+i+".jpg');");
					
					styleColor = "";
					if(Verticart.catalog.products[product].attributes.colors[i].txt){
						styleColor = " color: "+Verticart.catalog.products[product].attributes.colors[i].txt+";";
					}
					
					if(Verticart.catalog.products[product].attributes.colors[i].hex){
						n.setAttribute('style',"background-color: "+Verticart.catalog.products[product].attributes.colors[i].hex+";"+styleColor);
					} else {
						n.setAttribute('style',"background-color: "+i+";"+styleColor);
					}
					

					t = document.createTextNode(i);
					n.appendChild(t);
					$('color').appendChild( n );

				}
			}
		}
		
	}	
	
	/* SIZE */
	if($('size')){
		while( $('size').firstChild ) {
			$('size').removeChild( $('size').firstChild );
		}	
		if(Verticart.catalog.products[product]){
			for(i in Verticart.catalog.products[product].attributes.sizes){
				if(i){
					n = document.createElement('OPTION');
					n.value = i;
					n.appendChild( document.createTextNode( Verticart.catalog.products[product].attributes.sizes[i].name ) );
					$('size').appendChild( n );
				}
			}
		}
		update_price();
	}
	
}

function update_color(e) {
	//$('color').value = this.id;
	//alert(this.value);
	//$('color').value = this.value;
	/*
	var nodeList = $('product_list').childNodes;
	var i = 0;
	while( i < nodeList.length ) {
		nodeList[i].style.border = 'none';
		i++;
	}
	this.style.border = '2px solid #000';
	*/
	update_price();
}

function update_design(e) {
	
	if($('design').value == 'name' ){
		$('font').style.display = 'block';
	} else {
		$('font').style.display = 'none';
		$('font').value = '';
	}
	
}

function update_price() {
	var qty = $('quantity').value;
	var product = $('product').value;
	var size = $('size').value;
	var color = $('color').value;
	//var item_price = eval( "Verticart.catalog.products."+product+".attributes.sizes."+size+".price" );
	
	var p = Verticart.catalog.products[product];
	
	if(p == null){ return false; }
	
	var base_price = parseFloat(p.price);
	var size_price = 0;
	if(size){
		size_price = parseFloat(p.attributes.sizes[size].price);
	}
	var color_price = 0;
	if(color){
		color_price = parseFloat(p.attributes.colors[color].price);
	}
	//eval( "var item_price = parseFloat(Verticart.catalog.products."+product+".price) + parseFloat(Verticart.catalog.products."+product+".attributes.sizes."+size+".price) + parseFloat(Verticart.catalog.products."+product+".attributes.colors."+color+".price)" );
	var item_price = base_price+size_price+color_price;
	var subtotal = money(qty * (item_price * discount(qty)));
	var price = document.createElement('DIV');
	price.appendChild( document.createTextNode( '@ $' + money(item_price * discount(qty)) +'/ea. = $'+subtotal ) );
	removeChildren( $('price_block') );
	$('price_block').appendChild( price );
}

function discount(qty) {
	var discount = 1;
	var d = 1;
	if( qty > 14 ){
		var discount = d - 0.10;
	}
	/*
	if( qty > 11 ){
		var discount = d - 0.10;
	}
	if( qty > 23 ){
		var discount = d - 0.15;
	}
	if( qty > 47 ){
		var discount = d - 0.20;
	}
	*/
	return discount;
}

function shipping(qty) {
	var amt = 10.00 + (qty * 2)
	return money(amt);
}


function money(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function init() {

	
	
	if(location.search){

		//var design = YAHOO.util.History.getQueryStringParameter('design');
			//q = location.search.toQueryParams();
		//if(design){
		//	$('design').value = design;	
		//}
	}
	
	if($('design'))
	{
		//if($('design').value.match(/academy|athletics|baseball|hockey/) ){
			$('text_color').style.display = 'block';
			if($('design').value == 'name'){
				$('font').style.display = 'block';	
			}
		//}
	}
	
	if($('product'))
	{
		if(!$('product').value){
			$('product').value = 'hoodie';
		}
	}
	update_product();

	if($('color')){
		if($('color').value){
			update_price();	
		}
	}

	if($('name')){
		/*
		$('name').onfocus = function() {
			$('name').value = '';
		};
		*/
	}
	
	if($('buy')){
		$('buy').onclick = function() {
			var cart_update = true;
			if($('name').value && $('quantity').value){
				
			} else {
				alert('Be sure to input \"Your Name\" and \"Quantity\"');
				cart_update = false;
			}
			if($('color').value && $('text_color').value && $('text_color').value.toUpperCase() === $('color').value.toUpperCase()){
				confirm('Warning: This color combination may not show up well');
				cart_update = false;
			}
			
			if(cart_update){
				Verticart.cart.update();
			}

		};
	}
	

	
	$('product').onchange = function() { update_product(); };
	$('size').onchange = function() { update_price(); };
	$('color').onchange = function() { update_price(); };
	$('design').onchange = function() { update_design(); };
	$('quantity').onkeyup = function() { update_price(); };
	
	$('view_help').onclick = function() {
		$('help').style.display = 'block';
		$('config').style.display = 'none';
		$('output').style.display = 'none';
		$('cart').style.display = 'none';
	};
	
	$('view_config').onclick = function() {
		$('help').style.display = 'none';
		$('config').style.display = 'block';
		$('output').style.display = 'block';
		$('cart').style.display = 'none';
	};
	$('view_cart').onclick = function() {
		$('help').style.display = 'none';
		$('config').style.display = 'none';
		$('output').style.display = 'none';
		$('cart').style.display = 'block';
		Verticart.cart.display();
	};
	$('preview_button').onclick = function() {
		if($('name').value){
			$('help').style.display = 'none';
			$('config').style.display = 'block';
			$('output').style.display = 'block';
			$('cart').style.display = 'none';
			render();
		} else {
			alert('Please enter \"Your Name\"');
			$('name').focus();
		}
	};
}

var render_callback = {
	success: update_output,
	failure: function() { alert('An error occured while rendering...'); }
};

Verticart.catalog = {
	products: [],
	add: function( obj_product ) {
		eval("Verticart.catalog.products."+obj_product.code+" = obj_product");
	},
	connection: null,
	load_product: function( product_code ) {
		this.connection = YAHOO.util.Connect.asyncRequest('POST','/create-a-shirt/catalog.php',this.process,'product='+product_code);
	},
	load_check: function(request) {
		return YAHOO.util.Connect.isCallInProgress(request);
	},
	error: function() {
		alert('An error occured!');
	},
	process: {
		success: function(o) {
			var obj_product = o.responseText;
			Verticart.catalog.add( JSON.parse(obj_product) );
			/*alert(JSON.stringify(Verticart.catalog));*/
			
			init();			

			
		},
		failure: function(o) {
			alert('Verticart.catalog.load_product failed');
		}
	} 
};

Verticart.cart = {
	contents: [],
	add: function( obj_cart_item ) {
		obj_cart_item.price = this.get_price(obj_cart_item);
		var index = this.contents.length;
		this.contents[index] = obj_cart_item;
	},
	get_price: function(cart_item) { 
		//var p = cart_item.product;
		
		var p = Verticart.catalog.products[cart_item.product];
		
		var size = cart_item.size;
		var color = cart_item.color;
		
		var base_price = parseFloat(p.price);
		var size_price = 0;
		if(size){
			size_price = parseFloat(p.attributes.sizes[size].price);
		}
		var color_price = 0;
		if(color){
			color_price = parseFloat(p.attributes.colors[color].price);
		}
	
		var item_price = base_price+size_price+color_price;
		var subtotal = money( item_price * discount(cart_item.quantity) );
		return subtotal;
		//return eval( "money(Verticart.catalog.products."+ cart_item.product + ".attributes.sizes." + cart_item.size + ".price * discount(" + cart_item.quantity + "))");
	},
	display: function () {
		removeChildren( $('cart') )
		var c = document.createElement('DIV');
		c.style.margin = '0px';
		c.style.width = '640px';
		c.style.height = '480px';
		c.style.overflow = 'auto';
		var title = document.createElement('H1');
		title.style.margin = '10px';
		title.appendChild( document.createTextNode('Shopping Cart'));
		c.appendChild( title );
		var header = document.createElement('DIV');
		header.style.width = '640px';
		header.style.height = '20px';
		header.style.position = 'relative';
		header.style.backgroundColor = '#000077';
		fields = [];
		fields[0] = ['Product',40,410,'left'];
		fields[1] = ['Qty',430,40,'right'];
		fields[2] = ['Unit Price',470,80,'right'];
		fields[3] = ['Subtotal',550,80,'right'];
		var i = 0;
		while(i < fields.length){
			var field = document.createElement('DIV');
			field.style.position = 'absolute';
			field.style.top = '2px';
			var offset = fields[i][1];
			field.style.left = offset + 'px';
			field.style.width = fields[i][2] + 'px';
			field.style.fontWeight = 'bold';
			field.style.textAlign = fields[i][3];
			field.style.color = '#ffffff';
			//field.style.overflow = 'hidden';
			//field.style.whiteSpace = 'wrap';
			field.appendChild( document.createTextNode(fields[i][0]) );
			header.appendChild( field );
			i++;
		}
		c.appendChild( header );
		var i = 0;
		while(i < this.contents.length){
			var order_item = document.createElement('DIV');
			order_item.style.position = 'relative';
			order_item.style.height = '20px';
			
			font = '';
			if(Verticart.cart.contents[i].font){
				font = '/'+Verticart.cart.contents[i].font.toUpperCase();
			}
			text_color = '';
			if(this.contents[i].text_color){
				text_color = ' ('+this.contents[i].text_color.toUpperCase() + font + ') '; 
			}
			
			data = [
				this.contents[i].product.toUpperCase()+ '~' + 
				this.contents[i].size.toUpperCase()+ '~' + 
				this.contents[i].color.toUpperCase() + '~' + 
				this.contents[i].design.toUpperCase() + '~' +
				this.contents[i].name+text_color,
				this.contents[i].quantity,
				'$'+money( this.contents[i].price ),
				'$'+money(this.contents[i].quantity * this.contents[i].price )
			];
			
			var f = 0;
			while(f < fields.length){
			
				var item_field = document.createElement('DIV');
				item_field.style.position = 'absolute';
				item_field.style.top = '4px';
				item_field.style.left = fields[f][1] + 'px';
				item_field.style.width = fields[f][2] + 'px';
				item_field.style.textAlign = fields[f][3];
				
								
				item_field.style.height = '20px';
				
				item_field.style.overflow = 'hidden';
				
				item_field.style.border = '1px solid #eee';
				
				item_field.style.border = '1px solid #fff';
				item_field.appendChild( document.createTextNode(data[f]) );
				order_item.appendChild( item_field );
				
				f++;
			}

			/* delete_me */
			var delete_me = document.createElement('BUTTON');
			delete_me.style.position = 'absolute';
			delete_me.style.left = '0px';
			delete_me.style.margin = '6px';
			delete_me.style.border = '0px solid #000';
			delete_me.style.cursor = 'pointer';
			/*delete_me.onclick = this.contents[i].remove;*/
			delete_me.onclick = this.remove;
			
			delete_me.setAttribute('ID','order_item_'+i );
			delete_me.appendChild( document.createTextNode('X') );
			delete_me.style.backgroundColor = '#cc0000';
			delete_me.style.color = '#ffffff';
			
			order_item.appendChild( delete_me );
			
			c.appendChild( order_item );
			i++;
		} 
		
		
		var order_total = document.createElement('DIV');
		order_total.style.position = 'relative';
		order_total.style.width = '630px';
		order_total.style.borderTop = '1px solid #000';
		order_total.style.margin = '10px 0px 10px 0px';
		order_total.style.textAlign = 'right';
		order_total.style.paddingRight = '10px';
		
		
		
		var gtotal = 0;
		for(i in Verticart.cart.contents){
			gtotal = gtotal + money(Verticart.cart.contents[i].price * Verticart.cart.contents[i].quantity);
		}
		
		
		
		order_total.appendChild( document.createTextNode('(Shipping and Sales Tax are shown at checkout) Cart Total: $'+gtotal) );
			
		c.appendChild( order_total );
		
		/*
		<img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" align="left" style="margin-right:7px;">
		*/
		
		var checkout_button = document.createElement('INPUT');
		//checkout_button.appendChild( document.createTextNode('CHECKOUT') );
		checkout_button.type = 'image';
		checkout_button.src = 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif';
		/*
		checkout_button.style.color = '#ffffff';
		checkout_button.style.backgroundColor = '#00cc00';
		checkout_button.style.fontWeight = 'bold';
		checkout_button.style.border = '1px solid #000000';
		*/
		checkout_button.style.position = 'relative';
		checkout_button.style.bottom = '-20px';
		checkout_button.style.left = '480px';
		
		/*
		checkout_button.onclick = this.checkout;
		*/
		checkout_button.onclick = this.checkout_paypal;
		if(this.contents.length > 0){
			c.appendChild( checkout_button );
		}
		
		$('config').style.display = 'none';
		
		$('output').style.display = 'none';
		$('cart').appendChild( c );
		$('cart').style.display = 'block';
		return false;
		
	},
	update: function() {
		var cart_item = {
			name: $('name').value,	
			quantity: $('quantity').value,	
			product: $('product').value,
			design: $('design').value,
			color: $('color').value,
			text_color: $('text_color').value,
			font: $('font').value,
			size: $('size').value
		};
		Verticart.cart.add( cart_item );
		document.cookie = "cart=" + JSON.stringify( Verticart.cart );
		Verticart.cart.display();
		return false;
	},
	remove: function() {
		var id = this.id.replace('order_item_','');		
		contents = [];
		for(i=0; i < Verticart.cart.contents.length; i++){
			if(i == id){
				/*alert(id);*/
			} else {
				contents[contents.length] = Verticart.cart.contents[i];
			}
		}
		Verticart.cart.contents = contents;
		Verticart.cart.display();
		Verticart.cart.save_contents();
	},
	save_contents: function() {
		document.cookie = "cart=" + JSON.stringify( Verticart.cart );
	},
	load_contents: function() {
		if(get_cookie("cart")) {
			var json_cart_contents = JSON.parse(get_cookie("cart")).contents;
			Verticart.cart.contents = json_cart_contents;
		}		
	},
	checkout: function() {
		form = document.createElement('FORM');
		document.body.appendChild( form );
		form.action = 'https://www.verticart.com/checkout.php';
		form.method = 'POST';
		field = document.createElement('INPUT');
		field.type = 'text';
		field.name = 'cart';
		field.value = get_cookie('cart');
		alert(get_cookie('cart'));
		form.appendChild( field );
		form.submit();
	},
	checkout_paypal: function() {
		if(Verticart.cart.contents.length == 0){
			alert('Your order is empty.');
			return false;
		}
		form = document.createElement('FORM');
		document.body.appendChild( form );
		
		
		//form.action = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
		form.action = 'https://www.paypal.com/cgi-bin/webscr';
		form.target = '_blank';
		
		form.method = 'POST';
		var fields = [
			{
				type: "hidden",
				name: "cmd",
				value: "_cart"
			},
			
			{
				type: "hidden",
				name: "notify_url",
				value: "https://secure.extromedia.com/paypal/ipn_res.php"
			},
			/*
			{
				type: "hidden",
				name: "return",
				value: "https://secure.extromedia.com/paypal/ipn_res.php"
			},
			{
				type: "hidden",
				name: "rm",
				value: "2"
			},
			*/
			{
				type: "hidden",
				name: "upload",
				value: 1
			},
			{
				type: "hidden",
				name: "business",
				value: "yournamestuff"+"@"+"extromedia.com"
			}
		];
		/*
		field = document.createElement('INPUT');
		field.type = 'hidden';
		field.name = 'cmd';
		field.value = '_cart';
		form.appendChild( field );
		*/
		for(i in fields){
			field = document.createElement('INPUT');
			field.type = fields[i].type;
			field.name = fields[i].name;
			field.value = fields[i].value;
			form.appendChild( field );			
		}
		var cart_qty = 0;
		for(i in Verticart.cart.contents){
			var seq = eval(i) + 1;
			item_name = document.createElement('INPUT');
			item_name.type = 'hidden';
			item_name.name = 'item_name_'+seq;

			font = '';
			if(Verticart.cart.contents[i].font){
				font = '/'+Verticart.cart.contents[i].font.toUpperCase();
			}
			text_color = '';
			if(Verticart.cart.contents[i].text_color){
				text_color = ' ('+Verticart.cart.contents[i].text_color.toUpperCase() + font + ') '; 
			}
			
			item_name.value = 	Verticart.cart.contents[i].product.toUpperCase()+ '~' +
								Verticart.cart.contents[i].size.toUpperCase()+ '~' + 
								Verticart.cart.contents[i].color.toUpperCase() + '~' + 
								Verticart.cart.contents[i].design.toUpperCase() + '~' +
								Verticart.cart.contents[i].name + text_color
			form.appendChild( item_name );
			
			item_amount = document.createElement('INPUT');
			item_amount.type = 'hidden';
			item_amount.name = 'amount_'+seq;
			item_amount.value = money(Verticart.cart.contents[i].price);
			form.appendChild( item_amount );
			
			item_qty = document.createElement('INPUT');
			item_qty.type = 'hidden';
			item_qty.name = 'quantity_'+seq;
			item_qty.value = Verticart.cart.contents[i].quantity;
			form.appendChild( item_qty );
			cart_qty = cart_qty + eval(Verticart.cart.contents[i].quantity);
		}
		ship_total = document.createElement('INPUT');
		ship_total.type = 'hidden';
		ship_total.name = 'shipping_1';
		ship_total.value = shipping(cart_qty);
		form.appendChild( ship_total );		
		form.submit();
	}
};

