// 03/2010

// OJAF REVISED

var ojaf_session = {};
var ojaf_views = {};
var ojaf_inits = [];


/**
 * Cookie Utilities
**/
function ojaf_set_cookie(key,val){
		
	var expires = "";		

	if(arguments[2]){
		var date = new Date();
		date.setTime(date.getTime() + (arguments[2] * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();				
	}

	document.cookie = key + "=" + escape(val) + expires + "; path=/";
}

function ojaf_erase_cookie(key){
		
	set_cookie(key,"",-1);
}	
	
function ojaf_get_cookie(key){
				
	var matches = new RegExp(key + "=([^;]+)").exec(document.cookie);

	if(matches)
	return unescape(matches[1]);

	return null;
}

/**
 * GET Query Utilities
**/
function ojaf_get_query(key){
		
	var m = new RegExp(key + "=([^&#]+)").exec(document.URL);

	if(m) return unescape(m[1])
	      return null;
}


/**
 * JSON Utilities
**/
function ojaf_json_encode(obj){
		
	var type = typeof(obj);
	if(type == "string")
	return '"' + ojaf_slashes(obj) + '"';
	if(type == "boolean")
	return obj ? 'true' : 'false';
	if(type == "number")
	return obj;
	if(type == "object"){
		if(!obj) return null;

		var s = [];
		if(typeof(obj.length)=="number"){
			for(var i = 0; i < obj.length; i++){s.push(ojaf_json_encode(obj[i]))}
			return '[' + s.join(',') + ']';
		}else{
			for(var k in obj){s.push('"'+k+'"' + ':' + ojaf_json_encode(obj[k]))}
			return '{' + s.join(',') + '}';
		}
	}
	return null;
}

function ojaf_json_decode(json){

	return eval("(" + json + ")");
}

function ojaf_slashes(str) {
	
	str = str.replace(new RegExp("\\n","g"), " ")
	str = str.replace(/\\/g,'\\\\');
	//str = str.replace(/\'/g,'\\\'');
	str = str.replace(/\"/g,'\\"');
	str = str.replace(/\0/g,'\\0');
	return str;
}

function ojaf_strip_tags(str){

    return str.replace(/<\/?[^>]+>/gi, '');
}
	

function ojaf_session_open(){

	var json;

 	if(!(json = ojaf_get_cookie('SESSION')))
	return;
	
	ojaf_session = ojaf_json_decode(json);
}

function ojaf_session_close(){

	ojaf_set_cookie('SESSION', ojaf_json_encode(ojaf_session));	 
}

/**
 * DOM related utilities
**/
// get elements by id
function $(){
	var r = [];
	for(var i = 0; i < arguments.length; i++)
		r.push(typeof arguments[i] == 'string' ?
			document.getElementById(arguments[i]) 
			: arguments[i]);
	

	return r.length != 1 ? r : r[0];
}

// set innerhtml
function $H(id, str){
	$(id).innerHTML = str;
}

// get field value
function $V(id){
	return $(id).value;
}

// get select value
function $OV(id){
	var e = $(id);
	return e[e.selectedIndex].value;
}

// populate select
function $OP(id, opts){
	var e = $(id);
	for(var i = 0; i < opts.length; i++)
		e[e.length] = new Option(opts[i].text, opts[i].value);
}

// set select value
function $OS(id, val){
	var e = $(id);
	for(var i = 0; i < e.length; i++)
	if(e[i].value == val){
		e.selectedIndex = i;
		return;
	}
}

/**
 * Array extensions
**/
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
}


String.prototype.format = function(){
	var fmt = this;
	for(var i = 0; i < arguments.length; i++){
		fmt = fmt.replace(new RegExp('\\{(' + (i + 1) + ')\\}','g'), arguments[i]);
	}
	return fmt;	
}


/**
 * Application state management utilities
**/

function ojaf_view_dispatch(){

	var v = ojaf_get_query('__VS');

	if(!v || !ojaf_views[v])
	v = 'default';

	ojaf_session_open();

	for(var i = 0; i < ojaf_inits.length; i++)
	ojaf_inits[i]();


	ojaf_views[v]();

}

function ojaf_switch_view(){
	
	var q = ['__VS=' + arguments[0]];
 
	var p = document.URL.indexOf('?');

	var self = (p == -1) ? document.URL : document.URL.substr(0,p);

	// xtra parameters
	if(arguments[1]){
		for(var k in arguments[1])
		q.push(k + '=' + escape(arguments[1][k]));
	}

	ojaf_session_close();
		
	location.href = self + '?' + q.join('&');
	return;

}

function ojaf_register_views(obj){

	ojaf_views = obj;

	if(!ojaf_views['default'])
	ojaf_views['default'] = function(){};
}

function ojaf_register_inits(obj){
	
 	for(var i in obj)
	ojaf_inits.push(obj[i]);
}

/**
 * Quick Reference:
 
 $() = document.getElementById
 $H(x,y) = set innerHTML of x to y
 $V(x) = x.value
 $OV(x) = <select> value (option value)
 $OP(x,a) = populate <select> x with options in a, [{text:x,value:y},{text:k,value:j}...]
 $OS(x,v) = set <select> value to v
**/ 
 


var views = {};
var inits = {};


function activate_view(id){
	$(id).className='activeViewFrame';
}

function set_page_title(tit, inf){ //haha
	$H('page_title', tit);
	$H('page_info', inf);
	$('info_icon').style.visibility='visible';
}

function wizard_show(o){
	$('wizard_nav').style.visibility = o ? 'visible' : 'hidden';
}

function wizard_show_next(o){
	$('next_btn').style.display= o ? 'block' : 'none';
}

function wizard_enable_next(o){
	$('next_btn').disabled = !o;
}

function wizard_on_next(c){
	$('next_btn').onclick = c;
}

function currency(amount)
{
	return Math.abs(parseFloat(amount)).toFixed(2);
}

function basket_add(item){

	// create the basket if it doesnt exist
	if(typeof ojaf_session['basket'] != 'object')
	ojaf_session['basket'] = [];

	// add the item
	ojaf_session['basket'].push(item);
}

function basket_remove(i){

	// from item at index 'index'
	ojaf_session['basket'].remove(i);
		
}

function basket_empty(){
	return !ojaf_session['basket'] || ojaf_session['basket'].length == 0;
}

function get_subtotal(){

	var sum = 0;
	if(!ojaf_session['basket'])
	return 0.00;
	
	for(var i = 0; i < ojaf_session['basket'].length; i++){
		if(ojaf_session['basket'][i].id == null) continue;
		sum += ojaf_session['basket'][i].quantity * ProductList[ ojaf_session['basket'][i].id ].price
	}
	return sum;
}

function get_shipping(){
	var country = ojaf_session['scountry'] ? ojaf_session['scountry'] : 
				 (ojaf_session['bcountry'] ? ojaf_session['bcountry'] : 'United States')
	if(country == 'United States' || country == 'Canada')
	return ojaf_session['shipping'] == null ? 10.00 : parseFloat(ojaf_session['shipping']);
	else
	return 15.0 + 0.11 * get_subtotal();
}

function get_adminfee(){
	return get_subtotal() < 20.00 ? 5.00 : 0.00; 
}

function get_rushfee(){
	return ojaf_session['rush'] ? parseFloat(ojaf_session['rush']) : 0.00;
}

function get_total(){
	return get_subtotal() + get_shipping() + get_rushfee() + get_adminfee();
}

/***
 * Business logic implementation follows..
***/

function select_item(id){
	// save item id
	ojaf_session['item_id'] = id;

	// personal items go to text page
	if(ProductList[id].type == "personal")
		ojaf_switch_view('text');
	else
	// licensed items go to images
		ojaf_switch_view('image');
}

function select_image(cat, id){
	// save image id
	ojaf_session['image_id'] = [cat, id];
	
	// view basket summary
	ojaf_switch_view('quantity');
}

function select_text(){

	var text = [];
	var font = $OV('font');
	var font_color = $OV('font_color');
	var item_color = $OV('item_color');
	
	if(font_color == item_color){
		alert('Oops! Your font color is the same as your koozie color!')
		return;
	}
	
	for(var i = 1; i < 4; i++){ 
	   var txt = $V('line' + i);
	   if(/[!\?\.\-]{2,}/.test(txt)){
			if(!confirm("PLEASE NOTE: Line " + i + " contains repeated punctuation that will"+
				" diminish the size of the actual text when printed.\r\n\r\nOK = Keep it this way.\r\nCANCEL = Edit the text."))
			return;
	   }
		
	   text.push( txt );  
	 }
	
	// edit existing item in basket
	if(ojaf_session['edit_id'] != -1){
		var bix = ojaf_session['edit_id'];
		ojaf_session['basket'][bix]['text'] = text;
		ojaf_session['basket'][bix]['font'] = font;
		ojaf_session['basket'][bix]['font_color'] = font_color;
		ojaf_session['basket'][bix]['item_color'] = item_color;
		ojaf_switch_view('basket');
		return;
	}
	  
	 // save new item attributes
	ojaf_session['text'] = text;
	ojaf_session['font'] = font;
	ojaf_session['font_color'] = font_color;
	ojaf_session['item_color'] = item_color;
	ojaf_switch_view('quantity');
	
}

function certify_text(){
	var c = $('certify');
	if(c.checked){
		wizard_enable_next(true);
	}else{
		c.checked = false;
		wizard_enable_next(false);
	}
}

function update_preview(){

	// update the preview image when 
	var url = "preview.php?font={1}&font_rgb={2}&bg_rgb={3}&line1={4}&line2={5}&line3={6}";
	
	// load the new preview
	$('preview_image').src  = url.format($OV('font'), ColorList[ $OV('font_color') ], ColorList[ $OV('item_color') ], 
				escape($V('line1')), escape($V('line2')), escape($V('line3')) );

	
}

function select_quantity(){

	// base properties
	var qty = parseInt($V('quantity'));

	if(isNaN(qty) || qty == 0){
		alert("Oops! That's an invalid quantity.");
		return;
	}
	
	qty = Math.abs(qty);
	
	var item = {'id': ojaf_session['item_id'], 'quantity': qty};

	// dynamic properties
	if(ojaf_session['image_id'])
	   item['image_id'] = ojaf_session['image_id'];
	if(ojaf_session['text']){
	   item['text']       = ojaf_session['text'];
	   item['item_color'] = ojaf_session['item_color'];
	   item['font_color'] = ojaf_session['font_color'];
	   item['font']       = ojaf_session['font'];
	}
		   	
	// add the item
	basket_add(item);
	
	// clear session variables
	ojaf_session['item_id'] = null;
	ojaf_session['image_id'] = null;
	ojaf_session['text'] = null;
	ojaf_session['item_color'] = null;
	ojaf_session['font_color'] = null;
	ojaf_session['font'] = null;

	// view basket contents
	ojaf_switch_view('basket');
}	

function remove_item(i){
	
	basket_remove(i);
	ojaf_switch_view('basket');
}

function edit_item(i){

	ojaf_session['edit_id'] = i;
	ojaf_switch_view('text');
}

function update_basket(){
	
	for(var i = 0; i < ojaf_session['basket'].length; i++){
		var qty = parseInt( $V('item_{1}_qty'.format(i)) );
		if(!isNaN(qty)){
				if(qty == 0){
					basket_remove(i);
				}else{
					ojaf_session['basket'][i].quantity = Math.abs(qty);
				}
		}
	}
	
	ojaf_switch_view('basket');
	
}

function validate_info_form(){

	var vfields = ['fname','lname','email1','email2','addr1','state','city','zip','phone'];
	var err = false;

	for(var i = 0; i < vfields.length; i++){
		var e = $(vfields[i]);
		if(e.value.replace(" ", "") == ""){
			e.className = "regFieldErr";
			err = true;
		}else{
			e.className = "regField";
		}
	}
	
	// if any fields were blank, fail
	if(err)
	return false;
	
	// if the emails arent the same, fail
	if($V('email1') != $V('email2')){
		$('email2').className='regFieldErr';
		return false;
	}
	
	return true;

}

function save_info_form(prefix){
	
	var vfields = ['fname','lname','email1','addr1','addr2','company','state','city','zip','phone'];
	
	for(var i = 0; i < vfields.length; i++){
		ojaf_session[prefix + vfields[i]] = $(vfields[i]).value;
	}
	ojaf_session[prefix + 'country'] = $OV('country');
}

function load_info_form(prefix){

	var vfields = ['fname','lname','email1','addr1','addr2','company','state','city','zip','phone'];
	for(var i = 0; i < vfields.length; i++){
		$(vfields[i]).value = ojaf_session[prefix + vfields[i]];
	}
	$('email2').value = ojaf_session[prefix + 'email1'];
	$OS('country', ojaf_session[prefix + 'country']);

}

function save_billing(){

	if(!validate_info_form()){
		location.href = "#top";
		set_page_title("Billing Information", "<span style='color:red'>Please correct the highlighted fields.</span>");
		return;
	}
	
	// save the form with a prefix 's' in session variables
	save_info_form('b');
		
	// manually save payment type
	ojaf_session['paytype'] = $('paypal').checked ? 'paypal' 
								: ($('visa').checked ? 'visa' : 'mastercard');
	
	if(!$('shiptobill').checked && ojaf_session['sfname']){
		// lazy erase shipping info
		ojaf_session['sfname'] = null;
	}
	
	// complicated state transition logic.
	ojaf_switch_view($('shiptobill').checked ? 'shipping' : (ojaf_session['paytype']=='paypal' ? 'comments' : 'payment'));
	
}

function save_shipping(){

	if(!validate_info_form()){
		location.href = "#top";
		set_page_title("Shipping Information", "<span style='color:red'>Please correct the highlighted fields.</span>");
		return;
	}
	
	save_info_form('s');
	
	ojaf_switch_view(ojaf_session['paytype'] == 'paypal' ? 'comments' : 'payment');
}

function save_payment(){
	
	function vccnum(cc){
		var c = cc.replace(/[^0-9]+/g, "");
		return c.length == 16 ? c : false;
	}
	
	var ccnum = vccnum($V('ccnum'));
	if(!ccnum){
		alert('A valid credit card number is 16 digits.');
		return;
	}
	
	ojaf_session['ccnum'] = ccnum;
	ojaf_session['verif'] = $V('verif');
	ojaf_session['ccexp'] = [$OV('ccexpy'), $OV('ccexpm')];
	
	ojaf_switch_view('comments');
}

function save_comments(){

	ojaf_session['rush'] = $OV('rush');
	ojaf_session['shipping'] = $OV('shipping');
	ojaf_session['comments'] = $V('comments');
	
	ojaf_switch_view('summary');

}

function transmission_complete(flag){
	if(flag == -1){
		ojaf_switch_view('error');
		return;
	}
	
	if(ojaf_session['paytype'] == 'paypal'){
		$H('checkout_msg', 'Redirecting to PayPal...');
		document.process_paypal.amount.value = currency(get_total());
		
		//
		ojaf_session = {};
		ojaf_session_close();
		//
		document.process_paypal.submit();
	}else{
		//
		ojaf_session = {};
		//
		ojaf_switch_view('complete');
	}
	
}


/****************************************************************
 * Master view state handlers.
*****************************************************************/

views['debug'] = function(){
	
	document.write('<tt>' + ojaf_get_cookie('SESSION') + '</tt>');
	
}

views['default'] = function(){
	
	
	if(!ojaf_session['splash']){
		activate_view('splash_screen');
		set_page_title('Personalized Shopping', 'This shopping system allows you to personalize individual koozies.');
		
		//ojaf_session['splash'] = true;
		return;
	}
	
	activate_view('item_selection');
	set_page_title('Koozie Selection', '<b>Select a koozie</b> by clicking on its name or selecting \"Add Item\"');

	
	// reset edit flag
	ojaf_session['edit_id'] = -1;

	var html = "";
	var view = $('item_selection');
	var item_template = unescape(view.innerHTML); 

	view.innerHTML = '';

	for(var i = 0; i < ProductList.length; i++){
		
		
		view.innerHTML += item_template.format(ProductList[i].name, 
					     ProductList[i].price,
					     'src="' + ProductList[i].image + '"', 
					     ProductList[i].webpage,
					     ProductList[i].description,
					     i);
	}

}

views['image'] = function(){

	activate_view('image_selection');
	set_page_title('Image Selection', '<b>Click the image</b> that you would like on your koozie.');
	wizard_show(true);
	wizard_show_next(false);
	
	if(ojaf_session['item_id'] == null)
	location.href='./'

	var cat;
	// find the category
	for(var i = 0; i < ImageList.length; i++){
		if(ImageList[i].type == ProductList[ ojaf_session['item_id'] ].type){
			cat = i;
			break;
		}
	}

	var html = '<table cellpadding="2" width="100%"><tr>';
	
	for(var i = 0; i < ImageList[cat].images.length; i++){
		html += '<td><input type="image" src="{1}" onclick="select_image({2},{3})" /></td>'.format(ImageList[cat].images[i], cat, i);
		if((i + 1) % 3 == 0)
			html += '</tr><tr>'; 
	}

	html += '</tr></table>';

	$H('image_selection', html);

}

views['text'] = function(){

	activate_view('text_selection');
	set_page_title('Personalize Your Koozie', 'Select your colors, font and personalized text.');
	wizard_show(true);
	wizard_enable_next(false);
	wizard_on_next(select_text);
	
	var colors = [];
	var pid, bix = ojaf_session['edit_id']; // product id, basket index 
	
	if(bix != -1)
		pid = ojaf_session['basket'][ bix ].id;
	else
		pid = ojaf_session['item_id'];
	
	if(pid == null)
	location.href='./'

	for(var i = 0; i < ProductList[pid].colors.length; i++){
		colors.push({'text':  ProductList[pid].colors[i], 
	                 'value': ProductList[pid].colors[i] });
	}
	
	// populate the list
	$OP('item_color', colors);
	
	// uncheck the certify box
	$('certify').checked = false;
	
	// edit an item in the basket
	if(bix != -1){
		$OS('item_color', ojaf_session['basket'][bix]['item_color']);
		$OS('font_color', ojaf_session['basket'][bix]['font_color']);
		$OS('font', ojaf_session['basket'][bix]['font']);
		
		$('line1').value = ojaf_session['basket'][bix]['text'][0];
		$('line2').value = ojaf_session['basket'][bix]['text'][1];
		$('line3').value = ojaf_session['basket'][bix]['text'][2];
		//$('line4').value = ojaf_session['basket'][bix]['text'][3];
		
		// load the preview
		update_preview();
	}
	
}

views['quantity'] = function(){

	activate_view('quantity_selection');
	set_page_title('Quantity', 'How many of these would you would like added to your basket?');
	wizard_show(true);
	wizard_on_next(select_quantity);
	
	if(ojaf_session['item_id'] == null)
	location.href='./'
	
	$('quantity').focus();

}

views['basket'] = function(){

	activate_view('basket_view');
	set_page_title('My Basket', 'Continue shopping, change and remove items or checkout.');
	
	
	function pluralize(str, n){
		if(n <= 1) return str;
		if(str.charAt(str.length - 1) == "y")
			return str.substr(0, str.length - 1) + "ies";
		return str + "s";
	}
	
	/////////////
	//alert("A");
	/////////////
	
	// reset edit flag
	ojaf_session['edit_id'] = -1;
	
	var html = "";
	var msg = "";
	var total = get_subtotal();
	var admin = get_adminfee();
	
	if(!ojaf_session['basket'] || total <= 0){
		$H('basket_view', "<br /><br /><center>Your basket is empty: <a href='./'>Go shopping!</a></center><br /><br /><br />");
		return;
	}
	
	total += admin;
	
	var lic_tpl = unescape($('licensed_template').innerHTML);
	var per_tpl = unescape($('personal_template').innerHTML);
	
	
	for(var i = 0; i < ojaf_session['basket'].length; i++){


		// workaround the null id glitch
		if(ojaf_session['basket'][i].id == null)
		continue;
		
		
		if(ojaf_session['basket'][i]['text']){ 
			
			html += per_tpl.format(
					i,
					pluralize(ProductList[ ojaf_session['basket'][i].id ].name, ojaf_session['basket'][i].quantity),
					ProductList[ ojaf_session['basket'][i].id ].price,
					ojaf_session['basket'][i].quantity,
					ColorList[ ojaf_session['basket'][i].item_color ], // rgb
					ColorList[ ojaf_session['basket'][i].font_color ], // rgb
					ojaf_session['basket'][i].item_color, // name
					ojaf_session['basket'][i].font_color, // name
					ojaf_session['basket'][i].font,
					escape(ojaf_session['basket'][i].text[0]),
					escape(ojaf_session['basket'][i].text[1]),
					escape(ojaf_session['basket'][i].text[2]),
					ojaf_session['basket'][i].text[0],
					ojaf_session['basket'][i].text[1],
					ojaf_session['basket'][i].text[2]
					);
				
			
		}else{
			
			html += lic_tpl.format(
			        i,
					pluralize(ProductList[ ojaf_session['basket'][i].id ].name, ojaf_session['basket'][i].quantity),
					ProductList[ ojaf_session['basket'][i].id ].price,
					ojaf_session['basket'][i].quantity,
					'src="' + ImageList[ ojaf_session['basket'][i].image_id[0] ].images[ ojaf_session['basket'][i].image_id[1] ] + '"'
			);
			
		}
	}
	
	if(admin > 0){
			msg = "<input type='checkbox' id='adminfee' onclick=\"$('checkout_btn').disabled=!$('adminfee').checked\" /> <label for='adminfee'>I understand that because my order is under $20.00 it is subject to a $5.00 Administration Fee. (Included in the above total.)</label>";
			$('checkout_btn').disabled = true;
	}		
	

	html += $('basket_footer').innerHTML.format(currency(total), msg);
	
	// display
	$H('basket_view', html);

}

views['billing'] = function(){
	
	if(basket_empty()){
		location.href="./"
		return;
	}

	activate_view('billing_view');
	set_page_title('Billing Information', 'Please provide your billing address and payment method.');
	wizard_show(true);
	wizard_on_next(save_billing);
	
	if(ojaf_session['bfname'])
		load_info_form('b');
		
	$(ojaf_session['paytype']).checked = true;
	
}

views['shipping'] = function(){

	if(basket_empty()){
		location.href="./"
		return;
	}

	activate_view('billing_view');
	set_page_title('Shipping Information', 'Please provide your shipping information.');
	wizard_show(true);
	wizard_on_next(save_shipping);
	
	// dont need this UI for shipping
	$('billing_footer').style.display='none';
	
	if(ojaf_session['sfname'])
		load_info_form('s');
	
}

views['payment'] = function(){

	if(basket_empty()){
		location.href="./"
		return;
	}
	
	activate_view('payment_view');
	set_page_title('Payment Information', 'Please provide your credit card details.');
	wizard_show(true);
	wizard_on_next(save_payment);
	
	// credit card icon
	$('card_icon').src = 'icons/' + ojaf_session['paytype'] + '.png';
	
	if(ojaf_session['ccnum']){
		$('ccnum').value = ojaf_session['ccnum'];
		$('verif').value = ojaf_session['verif'];
		$OS('ccexpm', ojaf_session['ccexp'][1]);
		$OS('ccexpy', ojaf_session['ccexp'][0]);
	}
	
}

views['comments'] = function(){

	if(basket_empty()){
		location.href="./"
		return;
	}
	
	activate_view('comments_view')
	set_page_title('Additional Options', 'Select optional Rush Upgrades and add comments.')
	wizard_show(true);
	wizard_on_next(save_comments);
	
	// populate form with saved values
	if(ojaf_session['comments'] != null){
		$OS('rush', ojaf_session['rush']);
		$OS('shipping', ojaf_session['shipping']);
		$('comments').value = ojaf_session['comments'];
	}

}

views['summary'] = function(){

	if(basket_empty()){
		location.href="./"
		return;
	}
	
	activate_view('summary_view')
	set_page_title('Order Summary', 'Please review your order details before checking out.');
	wizard_show(true);
	wizard_on_next(function(){ojaf_switch_view('checkout')});
	$('next_btn').value = 'Checkout';
	
	$H('sum_bname', ojaf_session['bfname'] + ' ' + ojaf_session['blname']);
	$H('sum_bemail', ojaf_session['bemail1']);
	$H('sum_bphone', ojaf_session['bphone']);
	$H('sum_bcompany', ojaf_session['bcompany']);
	$H('sum_baddr', ojaf_session['baddr1'] + '<br />' + ojaf_session['baddr2']);
	$H('sum_bcity', ojaf_session['bcity']);
	$H('sum_bstate', ojaf_session['bstate']);
	$H('sum_bcountry', ojaf_session['bcountry']);
	$H('sum_bzip', ojaf_session['bzip']);
	
	$('sum_paytype').src = 'icons/' + ojaf_session['paytype'] + '.png'; 
	
	// payment information
	if(ojaf_session['paytype'] != 'paypal'){
		$('sum_ccinfo').style.display='block';
		$H('sum_ccnum', 'XXXX-XXXX-XXXX-' + ojaf_session['ccnum'].substr(12));
		$H('sum_ccexp', ojaf_session['ccexp'][1] + '/' + ojaf_session['ccexp'][0]);
	}
	
	// display the shipping info panel if needed
	if(ojaf_session['sfname'] && ojaf_session['sfname'] != ''){
		$('sum_sinfo').style.display='block';
		$H('sum_sname', ojaf_session['sfname'] + ' ' + ojaf_session['slname']);
		$H('sum_semail', ojaf_session['semail1']);
		$H('sum_sphone', ojaf_session['sphone']);
		$H('sum_scompany', ojaf_session['scompany']);
		$H('sum_saddr', ojaf_session['saddr1'] + '<br />' + ojaf_session['saddr2']);
		$H('sum_scity', ojaf_session['scity']);
		$H('sum_sstate', ojaf_session['sstate']);
		$H('sum_scountry', ojaf_session['scountry']);
		$H('sum_szip', ojaf_session['szip']);
	}
	
	// order totals
	$H('sum_total', currency(get_total()));
	$H('sum_ship', currency(get_shipping()));
	$H('sum_rush', currency(get_rushfee()));
	
}

views['checkout'] = function(){

	if(basket_empty()){
		location.href="./"
		return;
	}
	
	activate_view('checkout_view');
	set_page_title('Checkout', 'One moment while your order is being processed...');
	
	// expand session values out to send to server
	for(var i = 0; i < ojaf_session['basket'].length; i++){
		ojaf_session['basket'][i].name = ProductList[ ojaf_session['basket'][i].id ].name;
		if(ojaf_session['basket'][i].image_id){
			var img = ImageList[ ojaf_session['basket'][i].image_id[0] ].images[ ojaf_session['basket'][i].image_id[1] ];
			ojaf_session['basket'][i].image_name = img.substring(img.lastIndexOf("/")+1, img.lastIndexOf(".")); 
		}
	}
	
	ojaf_session['total'] = currency(get_total());
	ojaf_session['ship'] = currency(get_shipping());
	ojaf_session['rush'] = currency(get_rushfee());
	ojaf_session['admin'] = currency(get_adminfee());
	ojaf_session['subtotal'] = currency(get_subtotal());
	
	// encode the session and send it off
	document.process_order.xo.value = ojaf_json_encode(ojaf_session);
	$H('checkout_msg', 'Processing your order, one moment...');
	
	// set a safetey timer in case the hidden request times out
	setTimeout("ojaf_switch_view('error');", 30000); // 30 seconds
	
	document.process_order.submit();
	
}

views['complete'] = function(){
	activate_view('complete_view');
	set_page_title('Checkout Complete', 'Thank you for your order, checkout is complete.'); 
}

views['error'] = function(){
	activate_view('error_view');
	set_page_title('Checkout Error', 'Oops! Something went wrong during checkout.');
}


// tie view handlers into the OJAF
ojaf_register_views(views);
ojaf_register_inits(inits);


var ImageList=[
{name:"Licensed Can Cooler Images",
type:"lic-can-cooler",
images: ["/shopping/images/lic_can_cooler/coronalogo.jpg",
"/shopping/images/lic_can_cooler/mgdlogo.jpg",
"/shopping/images/lic_can_cooler/millerlitelogo.jpg"]},
{name:"Licensed Can Koozie Images",
type:"lic-can-koozie",
images: ["/shopping/images/lic_can_koozie/coronalogo.jpg",
"/shopping/images/lic_can_koozie/mgdlogo.jpg",
"/shopping/images/lic_can_koozie/millerlitelogo.jpg"]},
{name:"Licensed Foam Cooler Images",
type:"lic-foam-cooler",
images: ["/shopping/images/lic_foam_cooler/bud.jpg",
"/shopping/images/lic_foam_cooler/budlight.jpg",
"/shopping/images/lic_foam_cooler/coronanavyblue.jpg",
"/shopping/images/lic_foam_cooler/coronayellow.jpg",
"/shopping/images/lic_foam_cooler/mgd.jpg",
"/shopping/images/lic_foam_cooler/millerlite.jpg"]}];



var ProductList = 
[{name:"Beer Koozie",
price:12.99,
image:"/images/images.PNG/beer_bottle_koozies_3.png",
colors: ["Black", "Red", "Hot Pink", "Navy Blue", "Royal Blue", "Bright Orange", "Bright Yellow", "Neon Green", "Green", "Camouflage"],
webpage:"http://www.beerkoozies.com/koozies/beer-koozies.html",
type:"personal",
description:"Beer koozies are made from 3 mm neoprene (wetsuit material). They come with a zipper and a non skid rubber bottom. They fit standard long neck beer bottles."
},
{name:"Bottle Koozie",
price:12.99,
image:"/images/images.PNG/2010/bottle_bag.png",
colors: ["Black","Red","Royal Blue", "Green", "Fuschia", "Bright Orange","Bright Yellow"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"personal",
description:"Bottle koozies are made of 3mm neoprene (wetsuit material). They come with a draw string closure, a sewn in bottom and a handy swivel clip and belt loop for convenience. They fit 20oz. bottles and ½ litre bottles. Great for water, soda, beer and fruit drinks."
},
{name:"Collapsible Can Koozie",
price:9.99,
image:"/images/images.PNG/collapsible_can_koozies_4.png",
colors: ["Black",  "Red", "Steel Blue", "Navy Blue", "Burgundy","Fuschia","Purple","Jade", "Neon Green", "Bright Yellow", "Bright Orange",'Camouflage'],
webpage:"http://www.beerkoozies.com/koozies/",
type:"personal",
description:"Can Koozies are made from 3mm neoprene (wetsuit material). Can Koozies are collapsible and come with a bottom. They fit standard beer and soda cans."
},
{name:"The 40oz. Bottle Koozie",
price:14.99,
image:"/images/images.PNG/40oz_Bottle_Koozies.png",
colors: ["Black", "Navy Blue", "Bright Orange", "Camouflage"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"personal",
description:"The 40 oz. Bottle Koozie is made of 3mm neoprene (wetsuit material) It comes with a zipper and a glued-in non-skid bottom. It fits all 40 oz. beer bottles."
},
{name:"Wine Koozie",
price:14.99,
image:"/images/images.PNG/2010/wine-koozies.jpg",
colors: ["Black"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"personal",
description:"Wine Koozies are made of 3mm neoprene (wetsuit material). They fit all standard size wine bottles. They come with a zipper and a non skid bottom."
},
{name: "Jumbo Bottle Koozie",
price: 16.99,
image:"/images/images.PNG/2010/jumbo-koozies.jpg",
colors:["Burgundy","Green","Royal Blue","Red"],
webpage:"",
type:"personal",
description: "This premium neoprene koozie holds large bottles including one liter water bottles, one quart beer bottles and large sport drink bottles. It features an over-the-shoulder carry strap, zippered pocket, and draw string closure."
},
{name:"Golf Ball Caddy",
price:4.99,
image:"/images/images.PNG/2010/gbc.jpg",
colors:["Black","Green","Red","Royal Blue"],
webpage:"/koozies/",
type:"golf-ball-caddy",
description:"The Golf Ball Caddy is made of 3mm neoprene (wetsuit material), It holds 4 golf balls (not included) and two tees (inlcuded) clips on to the outside of any golf bag."
},
{name:"Non Collapsible Licensed Can Cooler",
price:5.99,
image:"/images/images.PNG/2010/licensedcancoolers.jpg",
colors: ["Mixed"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"lic-can-cooler",
description:"The Can Cooler is made of 5mm neoprene (wetsuit material) It has a glued in non-skid rubber bottom.        The Can Cooler holds bottles and cans. Available in Corona, MGD and Miller Lite."
},
{name:"Licensed Collapsible Can Koozie",
price:4.99,
image:"/images/images.PNG/licensed_collapsible_can_koozies_2.png",
colors: ["Mixed"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"lic-can-koozie",
description:"Can Koozies are made from 3mm neoprene. (wetsuit material).        Can Koozies are collapsible and come with a bottom. MGD, Miller Lite and Corona are available."
},
{name:"Licensed Foam Cooler",
price:3.99,
image:"/images/images.PNG/foam_coolers_2.png",
colors: ["Mixed"],
webpage:"http://www.beerkoozies.com/koozies/",
type:"lic-foam-cooler",
description:"Licensed Foam Coolers (not neoprene) are available with your favorite beer logos, Bud, Bud Lite, Miller Brands and Corona."
}
];

var ColorList = {
	'Black': '0,0,0', 
	'Red': '255,0,0', 
	'White': '255,255,255', 
	'Off White': '243,238,238', 
	'Hot Pink': '255,0,246', 
	'Steel Blue': '86,86,153',
	'Royal Blue': '11,3,161',
	'Navy Blue': '3,1,46',
	'Bright Orange': '255,108,0',
	'Bright Yellow': '255,255,0',
	'Neon Green': '16,255,0',
	'Dark Green': '2,60,19',
	'Green': '3,112,49',
	'Burgundy': '164,28,86',
	'Jade': '5,105,80',
	'Fuschia': '221,36,188',
	'Camouflage': '2,60,19',
	'Purple': '69,3,90'
};
