// Hoaphuongnam shopping cart
// Copyright (c) 2004 Hoaphuongnam. All rights reserved.
// This program is protected by copyright law and 
// international treaties. Unauthorized reproduction or 
// distribution of this program, or any portion of it, 
// may result in severe civil and criminal penalties, 
// and will be prosecuted to the maximum extent possible 
// under the law.


// global variables
var winvar = "width=680,height=350,menubar,scrollbars," +
		"location,resizable,status";
var myCookie; // cookie object
var cookieEnabled = false; // boolean value if the browser accept cookie or not
var id; // album ID
var title; // album title
var price; // album price
var qty; // quantity
var shFee = 0; // total qty
var cartTotal = 0; // total amount before s&h fee 
var totalAmnt = 0; // total amount due
var useCoupon = 0; // discount amount using valid coupon
var discount = 0; // the discount amount
var codeText; // coupon code
var baseAmntText; // amount spent to use coupon
var dscAmntText; // discount percent

// main function. Invoked whenever user click on the link
function DisplayCart ( albumTitle, albID, albPrice ) {
	// create cookie
	id = albID;
	title = albumTitle;
	price = albPrice;
	CreateCookieObj( albID );
	window.open ( "/hpncart.html", "hpncart", winvar );
}

// detect browser with cookie enabled
function DetectCookieEnabled( ) {
	// test once, skip the test the next time around
	if( ! cookieEnabled ) {
		// try to store a cookie
		CreateCookieObj( );
		// failed to set a cookie on browser
		if( ! cookieEnabled ) {
		document.writeln('This site uses cookies, and won\'t function properly without them. However, they are currently being <b>turned off</b>, please follow the instruction below to turn them on to continue.' + "<br/><br/>For Internet Explorer:<br/>Click on Tools -> Internet Options ... -> choose Security tab then lower the setting slider to minimum until you see the message 'Accept All Cookies' -> click on Apply then OK" + '<br/><br/>For Netscape/Mozilla:<br/>Click on Edit (or Tools) -> Preferences ... -> Choose Privacy & Security (on left panel) -> Cookies then choose Enable all Cookies, click OK<br/><br/>' ); 
		}
	}
}

// parse discount code xml file
function ParseXML( ) {
	var xml;
	xml = "" + "<?xml version=\"1.0\"?>"
	+ "<rootnode>" + "<code>" + "cn6am5"
	+ "</code>" + "<baseAmnt>" + "25"
	+ "</baseAmnt>" + "<dscAmnt>" + "0.15"
	+ "</dscAmnt>" + "</rootnode>";

	var objDom = new XMLDoc( xml, xmlError );
	var objDomTree = objDom.docNode;
	var code = objDomTree.getElements("code");
	var baseAmnt = objDomTree.getElements("baseAmnt");
	var dscAmnt = objDomTree.getElements("dscAmnt");

	var element = code[0];
	codeText = element.getText( );
	element = baseAmnt[0];
	baseAmntText = element.getText( );
	element = dscAmnt[0];
	dscAmntText = element.getText( );
}

// show the error if there is any from the xml file
// hardly this function will be ever called unless
// I was so damn drunk creating the xml file ;-)
function xmlError( e ) {
	alert( e );
}

// init cookie data
function _Init_data( incrementQty ) {
	myCookie.albID = id;
	myCookie.title = title;
	myCookie.price = price;
	myCookie.coupon = ''; // space
	if( incrementQty ) myCookie.qty++; else myCookie.qty = 1;
	myCookie.store( );
}

function DisplayCartContent( ) {
	// dummy cookie
	new CreateCookie( );
	CreateCookie.prototype.store = _Cookie_store;
	CreateCookie.prototype.load = _Cookie_load;
	CreateCookie.prototype.remove = _Cookie_remove;

	// paypal stuff
	document.writeln( '<input type="hidden" name="cmd" value="_cart">' );
	document.writeln( '<input type="hidden" name="upload" value="1">' );
	document.writeln( '<input type="hidden" name="business" value="getopts@yahoo.com">' );
	document.writeln( '<input type="hidden" name="return" value="http://www.hoaphuongnam.com/music/merchandise?action=thankyou">' );
	document.writeln( '<input type="hidden" name="cancel_return" value="http://www.hoaphuongnam.com/music/merchandise?action=canceledOrder">' );
	document.writeln( '<input type="hidden" name="rm" value="1">' );

	// hold up to 15 cookies
	var coupon = '';
	var itemNo = 0;
	for( var i = 0; i <= 14; i++ ) {
		myCookie = new CreateCookie( document, "hpncart" + i );
			if( ! myCookie.load( ) ) { 
				break;
			} else {
				// set coupon
				if( coupon.length == 0 ) { coupon = myCookie.coupon; }
				if( myCookie.qty <= 0 ) { continue; }
				var qty = parseInt( myCookie.qty );
				shFee += (qty * 1.50); // total amount of s&h cost
				var price = myCookie.price; 
				var itemPrice = (price * qty);
				cartTotal += (price * qty);
				totalAmnt = shFee + cartTotal;
				
				// start paypal stuff
				// print out these following lines up to the
				// number of quatity of item(s) ordered
				for( var n = 1 ; n <= qty; n++ ) { 
				// the order of item
				itemNo++;
				document.writeln( '<input type="hidden" name="item_name_' + itemNo + '" value="' + myCookie.title + '">' );
				document.writeln( '<input type="hidden" name="item_number_' + itemNo + '" value="' + myCookie.albID + '">' );
				document.writeln( '<input type="hidden" name="amount_' + itemNo + '" value="' + price + '">' );
				}
				// end of paypal stuff

				document.writeln( '<input type="hidden" name="albID" value="' + myCookie.albID + '">');
				document.writeln( '<tr><td style="vertical-align: top;" width="10%"><center><input type="text" name="qty" size="2" value="' + qty + '"></center></td>' );	
				document.writeln( '<td style="vertical-algin: top;" width="10%"><center><input type="checkbox" name="removes" value="' + myCookie.albID + '"></center></td>');
				document.writeln( '<td style="vertical-algin: top;" width="50%"><b>' + myCookie.title + '</b><br/>#' + myCookie.albID + '</td>');
				document.writeln( '<td style="vertical-algin: top;" width="20%">' + myCookie.price + ' USD</td>');
				document.writeln( '</tr>' );
			}
	}
	document.writeln( '</table><table cellpadding="2" cellspacing="2" border="0" style="width: 100%; text-align: left;"><tr><td style="vertical-align: top; text-align: left;" width="50%">Coupon: <input type="text" name="coupon" size="15" ' ); 
	if( (coupon.length > 0 ) && ( CheckCoupon( coupon ) > 0 ) ) {
		document.writeln( 'value="' + coupon + '" maxlength="30">' );
	} else if( ( coupon.length > 0 ) && ! CheckCoupon( coupon )) {
	// let the customer know the minimum amount spent to use this coupon
		document.writeln( 'value="' + coupon + '" maxlength="30"><br/>*The required minimum amount of <b>' + baseAmntText + '</b> USD <br/>spent before this coupon could be used.' );
	} else if( ( coupon.length > 0 ) && ( CheckCoupon( coupon ) == 'invalid' ) ) {
		document.writeln( 'maxlength="30"><br/><b>Invalid coupon</b>' );
	} else {
		document.writeln( 'maxlength="30">' );
	}

	// paypal stuff
	var discountShippingFee = 0; // the shipping minus any discount that applied
	if( useCoupon > 0 ) {
		discountShippingFee = ( shFee - useCoupon ); 
		if( discountShippingFee <= 0 ) { discountShippingFee = 0; }
		document.writeln( '<input type="hidden" name="shipping" value="' + _FormatDec( discountShippingFee ) + '">' );
	} else if( discount > 0 ) { 
		discountShippingFee = ( shFee - discount ); 
		if( discountShippingFee <= 0 ) { discountShippingFee = 0; }
		document.writeln( '<input type="hidden" name="shipping" value="' + _FormatDec( discountShippingFee ) + '">' );
	}else {
		document.writeln( '<input type="hidden" name="shipping" value="' + shFee + '">' );
	}

 	document.writeln( '</td><td style="vertical-align: top; text-align: right;" width="50%">' + '<input type="button" value="Update Cart" onClick="UpdateCart( ); location.reload( 1 );" class="smallbutton">' + '<input type="submit" value="Check Out"" class="smallbutton"></td></tr></table><br/>' );
}

// format a decimal number to print
function _FormatDec( decNumber ) {
	var n = Math.pow( 10.0, 2 );
	var i = Math.round( decNumber*n );
	var num = ( parseFloat( i )/n ).toString( );

	return num;
}

// cart total
function CartTotal( ) {
	var num = _FormatDec( cartTotal );
	document.writeln( num );	
}

// shipping and handling cost 
function ShippingCost( ) {
	document.writeln( shFee );	
}

// total amount due
function Total( ) {
	// users have valid coupon
	var num = _FormatDec( totalAmnt );
	document.writeln( '<b>' + num + '</b>' );	
}

// apply discount for valid coupon, purchase over certaint amount
function CalculateDiscount( ) {

	// customer making a purchase over $50, take 10% off
	if( cartTotal >= 100 ) {
		discount = ( cartTotal * 0.15 );
		document.writeln( '@ 15% &nbsp;&nbsp;&nbsp;<b>' + _FormatDec( discount ) + '</b>' );
		totalAmnt = ( totalAmnt - _FormatDec( discount ));

		return; 
	} else if( cartTotal >= 50 ) {
		discount = ( cartTotal * 0.1 );
		document.writeln( '@ 10% &nbsp;&nbsp;&nbsp;<b>' + _FormatDec( discount ) + '</b>' );
		totalAmnt = ( totalAmnt - discount );

		return; 
	} else if( useCoupon ) {
		document.writeln( '@ ' + dscAmntText*100 + '% with coupon &nbsp;&nbsp;&nbsp<b>' +_FormatDec( useCoupon ) + '</b>' );
		totalAmnt = ( totalAmnt - useCoupon );
		
		return;
	} else {
		document.writeln( 0 );
		return;
	}
}

// check for valid coupon
function CheckCoupon( coupon ) {
	//if( ! coupon ) {
	//	var coupon = document.hpncart.coupon.value;
	//	// check for valid coupon and apply the discount
	//	if( coupon.toUpperCase( ) == codeText.toUpperCase( ) && cartTotal >= parseInt( baseAmntText ) ) {
	//	// this is coupon code
	//		return coupon;
	//	} else if( coupon.toUpperCase( ) == codeText.toUpperCase( ) ) {
	//		return coupon;
	//	} else {
	//		return '';
	//	}
	// return the discount amount if the coupon is valid and the amount spent greater
	// or equal to the amount required to use the coupon
	if( coupon.toUpperCase( ) == codeText.toUpperCase( ) && cartTotal >= parseInt( baseAmntText ) ) {
		useCoupon = ( cartTotal * dscAmntText );
		return useCoupon;
	// return 0 if user enter a invalid coupon so that the DisplayCartContent() knows
	// to display appropriate msg. (i.e: this msg only being display when user actually
	// enter a code, otherwise, displays nothing
	} else if( coupon.toUpperCase( ) != codeText.toUpperCase( ) ) {
		return 'invalid';
	} else {
		return '';
	}
}

// update cart content
function UpdateCart( ) {
	// dummy cookie
	new CreateCookie( );
	CreateCookie.prototype.store = _Cookie_store;
	CreateCookie.prototype.load = _Cookie_load;
	CreateCookie.prototype.remove = _Cookie_remove;

	// loop through checkbox items to get an array of any checked box(es)
	var albRemoves = new Array( ); // id of albums to be removed
	var amtQty = new Array( ); // new qty amount
	var albID = new Array( );
	if( ! document.hpncart.removes ) return;
	var docLength = eval("document.hpncart.removes.length");
	if( typeof docLength == 'undefined' ) {
		if( eval("document.hpncart.removes.checked") ) {
			albRemoves[0] = document.hpncart.removes.value;
		} else {
			albRemoves[0] = 0;
		}
		amtQty[0] = document.hpncart.qty.value;
		if( amtQty[0] <= 0 || isNaN( amtQty[0] ) ) amtQty[0] = 0;
		albID[0] = document.hpncart.albID.value;
	} else {
	for( var i = 0; i < docLength; i++ ) {
		if( document.hpncart.removes[i].checked ) {
			albRemoves[i] = document.hpncart.removes[i].value;
		} else {
			albRemoves[i] = 0;
		}
		amtQty[i] = document.hpncart.qty[i].value;	
		if( amtQty[i] <= 0 || isNaN( amtQty[i] ) ) amtQty[i] = 0;
		albID[i] = document.hpncart.albID[i].value;
	}
	}
	//var coupon = CheckCoupon( );
	var coupon = document.hpncart.coupon.value;
	
	for( var i = 0; i <= 14; i++ ) {
		myCookie = new CreateCookie( document, "hpncart" + i );
			if( ! myCookie.load( ) ) { 
				break;
			} else {
				for( var n = 0; n < albID.length; n++ ) {
				if( ( myCookie.albID == albRemoves[n] ) || ( albID[n] == myCookie.albID && parseInt( amtQty[n] ) == 0 ) || ( albID[n] == myCookie.albID && amtQty[n] == null ) ) {
					// remove box checked, set qty = 0 
					myCookie.qty = 0
					if( myCookie.coupon.length == 0 || myCookie.coupon != coupon ) {
						myCookie.coupon = coupon;
					}
					myCookie.store( );	
					break;
				} else if( myCookie.albID == albID[n] ) {
					myCookie.qty = parseInt( amtQty[n] );
					if( myCookie.coupon.length == 0 || myCookie.coupon != coupon ) {
						myCookie.coupon = coupon;
					}
					myCookie.store( );
				}
			}
			}
	}
}

// Constructor: creates a cookie object for the specified doc
function CreateCookie( document, name, hours, path, domain, secure ) {
	// all the predifined properties begin with '$'
	this.$document = document;
	this.$name = name;
	if( hours ) this.$expiration = new Date((new Date()).getTime() + 3600000);
	this.$path = '/';
	if( domain ) this.$domain = domain; else this.$domain = null;
	if( secure ) this.$secure = true; else this.$secure = false;
}

// internal function, never call it explicitly
function _Cookie_store( ) {
	//loop throught the cookie object and get the values of the cookie
	var cookieval = "";
	for( var prop in this ) {
		// ignore properties with names begin with '$' or function
		if( (prop.charAt(0) == '$') || ( (typeof this[prop]) == 'function') ) {
			continue;
		}

		if( cookieval != "" ) cookieval += '&';
			cookieval += prop + ':' + escape( this[prop] );
	}
	// put together a complete cookie string
	var cookie = this.$name + '=' + cookieval;
	if( this.$expiration ) {
		cookie += '; expires=' + this.$expiration.toGMTString();
	}

	if( this.$path ) {
		cookie += '; path=' + this.$path;
	}

	if( this.$secure ) {
		cookie += '; secure';
	}

	// dumping cookie for debugging
	// alert( cookie.length + " chars - " + cookie );
	// now store the cookie
	this.$document.cookie = cookie;
}

// internal function, never call it explicitly
function _Cookie_load( ) {
	// get all cookies pertain to this doc
	var allcookies = this.$document.cookie;
	if( allcookies == "" ) return false;

	// extract just the name cookie in the list
	var start = allcookies.indexOf( this.$name + '=' );
	if( start == -1 ) { return false; }
	start += this.$name.length + 1;
	var end = allcookies.indexOf(';', start);
	if( end == -1 ) end = allcookies.length;
	var cookieval = allcookies.substring( start, end );

	// get value of the named cookie
	var a = cookieval.split( '&' );
	for( var i=0; i<a.length; i++ ) {
		a[i] = a[i].split(':');
	}

	for( var i=0; i<a.length; i++ ) {
		this[a[i][0]] = unescape( a[i][1] );
	}

	// done, return success code
	return true;
}

// internal function, never call it explicitly
function _Cookie_remove( ) {
	var cookie;
	cookie = this.$name + '=';
	if( this.$path ) cookie += '; path=' + this.$path;
	if( this.$domain ) cookie += '; domain=' + this.$domain;
	cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

	this.$document.cookie = cookie;
}

// get cookies
function CreateCookieObj( albID ) {
	// dummy cookie
	new CreateCookie( );
	CreateCookie.prototype.store = _Cookie_store;
	CreateCookie.prototype.load = _Cookie_load;
	CreateCookie.prototype.remove = _Cookie_remove;

	// test if the browser has cookie enabled
	if( ! albID ) {
		myCookie = new CreateCookie( document, "testcookie" );
		myCookie.enabled = 1;
		myCookie.store ( );

		// get back the cookie to test if it was stored successfully
		myCookie = new CreateCookie( document, "testcookie" );
		if( myCookie.load( ) && myCookie.enabled ) {
			// browser accepts cookie, set the global var to true
			// and remove the cookie
			cookieEnabled = true;
			myCookie.remove( );
			return;
		}
		return;
	}

	// store the cookie
	for( var i = 0; i < 14; i++ ) {
		myCookie = new CreateCookie( document, "hpncart" + i);
		if( ! myCookie.load( ) ) {
			_Init_data( );
			break;
		} else {
			if( myCookie.albID == albID ) {
				_Init_data( true );
				break;
			}
		}
	}
}
