function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

addEvent(window,'unload',EventCache.flush);


/* Expand/collapse divs */

function switchMenu(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != "none" ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

function expandOnce(obj) {
	var el = document.getElementById(obj);
	var el2 = document.getElementById(obj + "link");
	if ( el.style.display != "none" ) {
		el.style.display = 'none';
		el2.style.display = '';
	}
	else {
		el.style.display = '';
		el2.style.display = 'none';
	}
}

function $() {
	var elements = new Array();
	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 collapseAll(objs) {
	var i;
	for (i=0;i<objs.length;i++ ) {
		objs[i].style.display = 'none';
	}
}

/*
function pageLoad() {
	collapseAll($('example1','example1b','example2','example3'));
}

addEvent(window,'load',pageLoad); */


function QueryString(key) { 
	var value = null; 
	for (var i=0;i<QueryString.keys.length;i++) { 
		if (QueryString.keys[i]==key) { 
			value = QueryString.values[i]; 
			break; 
		} 
	} 
	return value; 
}

QueryString.keys = new Array(); 
QueryString.values = new Array();

function QueryString_parse() { 
	var query = window.location.search.substring(1); 
	var pairs = query.split("&");
	for (var i=0;i<pairs.length;i++) { 
		var pos = pairs[i].indexOf('='); 
		if (pos >= 0) { 
			var argname = pairs[i].substring(0,pos); 
			var value = pairs[i].substring(pos+1); 
			QueryString.keys[QueryString.keys.length] = argname; 
			QueryString.values[QueryString.values.length] = value; 
		} 
	} 
}

QueryString_parse(); 


function getValueFromHash(variable) { 
    var hashvalue = document.location.hash;
    var vars = hashvalue.split("&"); 
    
    for (var i=0;i<vars.length;i++) { 
        var pair = vars[i].split("="); 
        if (pair[0] == variable) return pair[1]; 
    } 
  
    return 0;
} 


function yearbookCalcWithHash() {
    var i = 0;
    
	var quantity = getValueFromHash('#quantity');
	var colorpages = getValueFromHash('colorpages');
	var bwpages = getValueFromHash('bwpages');
	var bindingtype = getValueFromHash('bindingtype');
    
    if (quantity > 0) {
    
        // Set values
        document.getElementById('yc.quantity').value = quantity;
        document.getElementById('yc.colorpages').value = colorpages;
        document.getElementById('yc.bwpages').value = bwpages;
        document.getElementById('yc.binding').selectedIndex = bindingtype;		
        
        while (document.getElementById('yc.salesprint' + i)) {
            document.getElementById('yc.salesprint' + i).selectedIndex = getValueFromHash('adprinttype' + i);
            
            document.getElementById('yc.piecespage' + i).value = getValueFromHash('piecesperpage' + i);		
            document.getElementById('yc.price' + i).value = getValueFromHash('priceperpiece' + i);		
            document.getElementById('yc.sales' + i).value = getValueFromHash('adsales' + i);
            
            i++;
        }
    }
    
    

    
    yearbookCalc();
    
}

function yearbookCalc() {
		
		// Pricing data
	var colorpageprice = 0.18,
		bwpageprice = 0.04,
		blankpageprice = 0.02,
		perfectbindprice = 2.15,
		coilbindprice = 1.61,
		bookletbindprice = 1.07,
		designfee48 = 3000,
		designfeeincrement = 150,
		designfeeincrementquantity = 4,
		printfee149 = 2.0,
		printfee199 = 1.75,
		printfee249 = 1.60,
		printfee299 = 1.35,
		printfeemax = 1.15,
		perfectbindtype = 0,
		coilbindtype = 1,
		bookletbindtype = 2,		
		
	var quantity = parseInt(document.getElementById('yc.quantity').value, 10),
		colorpages = parseInt(document.getElementById('yc.colorpages').value, 10),
		bwpages = parseInt(document.getElementById('yc.bwpages').value, 10),
		bindingtype = document.getElementById('yc.binding').selectedIndex;

	var designfee = 0,
		printfee = 0,
		colorpagesbook = 0,
		bwpagesbook = 0,
		blankpagesbook = 0,
		blankpagesbookcost = 0,
				
		pagecount = 0,
		pagecountcontent = 0,
		
		recycledbook = 0,
		
		totalbook = 0,
		total = 0;
		
	var errortext = '';
		
    if (isNaN(quantity)) quantity = 0;
    if (isNaN(colorpages)) colorpages = 0;
    if (isNaN(bwpages)) bwpages = 0;    
    
    
    
	// Reset error labels
	showErrorInLabel('yc.quantitylabel', false);
	showErrorInLabel('yc.colorpageslabel', false);
	showErrorInLabel('yc.bwpageslabel', false);
	showErrorInLabel('yc.bindinglabel', false);
	showErrorInLabel('yc.designfeelabel', false);
	showErrorInLabel('yc.totallabel', false);
		
    
	
	// Determine various values
	pagecountcontent = Math.floor(colorpages + bwpages);
	
	if (pagecountcontent <= 48) {
		designfee = designfee48;
	}
	else {
		designfee = designfee48 + (designfeeincrement * Math.ceil((pagecountcontent - 48) / designfeeincrementquantity));
	}
	
	if (quantity < 150) {
		printfee = printfee149;
	}
	else if (quantity < 200) {
		printfee = printfee199;
	}
	else if (quantity < 250) {
		printfee = printfee249;
	}
	else if (quantity < 300) {
		printfee = printfee299;
	}
	else {
		printfee = printfeemax;
	}
	
	colorpagesbook = colorpages * colorpageprice;
	bwpagesbook = bwpages * bwpageprice;



	// Build arrays for ad pages info
	var piecesperpage = [],
		priceperpiece = [],
		adsales = [],
		adprinttype = [],
		
		adpagecost = [],
		adpagesrequired = [],
		bookadprofit = [],
		
		adpagescolor = 0,
		adpagesbw = 0,
		adpagepricetotal = 0,
		bookadprofittotal = 0,
		bookadrevenuetotal = 0,
		
		index = 0,
		count = 0,
		i = 0;
		
	while (document.getElementById('yc.piecespage' + i)) {
		piecesperpage[i] = parseInt(document.getElementById('yc.piecespage' + i).value, 10);
		priceperpiece[i] = parseFloat(document.getElementById('yc.price' + i).value);
		adsales[i] = parseInt(document.getElementById('yc.sales' + i).value, 10);
        
        if (isNaN(piecesperpage[i])) piecesperpage[i] = 0;
        if (isNaN(priceperpiece[i])) priceperpiece[i] = 0;
        if (isNaN(adsales[i])) adsales[i] = 0;    
        
		i++;
		count++;
	}

    
	
	// Calculate advertising stuff
	for (i = 0; i < count; i++) {
		index = document.getElementById('yc.salesprint' + i).selectedIndex;
        
        adprinttype[i] = index;
        
        // index = 0 is none, 1 is color, 2 is bw
		// If ad type is "none" the rest of the entries on the line don't matter.
		if (index == 0) {
			adpagecost[i] = 0;
			adpagesrequired[i] = 0;
			bookadprofit[i] = 0;
			continue;
		}
        
		adpagecost[i] = (index == 1 ?  colorpageprice : bwpageprice);
		adpagesrequired[i] = (piecesperpage[i] != 0 ? Math.ceil(adsales[i] / piecesperpage[i]) : 0);
        
		if (index == 1) adpagescolor += adpagesrequired[i];
		else adpagesbw += adpagesrequired[i];
		
		adpagepricetotal += adpagesrequired[i] * adpagecost[i];
				
		bookadprofit[i] = ((priceperpiece[i] * adsales[i]) / quantity) - (adpagesrequired[i] * adpagecost[i]);
		
		bookadprofittotal += bookadprofit[i];
		
		bookadrevenuetotal += ((priceperpiece[i] * adsales[i]) / quantity);
	}




	pagecount = pagecountcontent + adpagescolor + adpagesbw;
    
    
    
    
    
    
	// Happy fun error checking time
    
    
	// Quantity should be between 150 and 500
	if (quantity > 500) {
		errortext += "Order quantity must be between 100 and 500 (contact us for a custom quote if you need a larger quantity). ";
		
		showErrorInLabel('yc.quantitylabel', true);
	}
	if (quantity < 150) {
		errortext += "Order quantity must be between 150 and 500 (contact us for a custom quote if you need a smaller quantity). ";
		
		showErrorInLabel('yc.quantitylabel', true);
	}
		
	// Printed page count should be between 36 and 90
	if (colorpages + bwpages > 90) {
		errortext += "The total number of pages (excluding advertising) must be between 36 and 90 (contact us for a custom quote if you need a larger number of pages). ";
		
		showErrorInLabel('yc.colorpageslabel', true);
		showErrorInLabel('yc.bwpageslabel', true);
	}
	if (colorpages + bwpages < 36) {
		errortext += "The total number of pages (excluding advertising) must be between 36 and 90 (contact us for a custom quote if you need a smaller number of pages). ";
		
		showErrorInLabel('yc.colorpageslabel', true);
		showErrorInLabel('yc.bwpageslabel', true);
	}
    

	
	switch (bindingtype) {
		case coilbindtype:
			bindingbook = coilbindprice;
		
			// Add our included blank pages
			blankpagesbook = 6;
			pagecount += blankpagesbook;
			
			break;
			
		case perfectbindtype:
			bindingbook = perfectbindprice;
		
			// Add our included blank pages
			blankpagesbook = 6;
			pagecount += blankpagesbook;
			
			if (pagecount < 40) {
				errortext += "You must have at least 40 pages total to use perfect binding. ";
				
				showErrorInLabel('yc.bindinglabel', true);
			}
			break;
		
		case bookletbindtype:
            var addedpages = 0;
            
			bindingbook = bookletbindprice;
		
			if (pagecount > 68) {
				errortext += "You can't have more than 68 pages in a booklet binding. ";
				
				showErrorInLabel('yc.bindinglabel', true);

				break;
			}
            
			if ((colorpages + adpagescolor) % 2 != 0 || (bwpages + adpagesbw) % 2 != 0) {
                
                blankpagesbook += (colorpages + adpagescolor) % 2;
                blankpagesbookcost += ((colorpages + adpagescolor) % 2) * colorpageprice;
                
                blankpagesbook += (bwpages + adpagesbw) % 2;
                blankpagesbookcost += ((bwpages + adpagesbw) % 2) * bwpageprice;
            
				errortext += "Booklet binding requires an even number of both color and black and white pages (each printed sheet is folded into two pages). ";
				addedpages = 1;
			}
			
            if ((pagecount + blankpagesbook) % 4 != 0) {
                blankpagesbookcost += ((pagecount + blankpagesbook) % 4) * bwpageprice;
                blankpagesbook += (pagecount + blankpagesbook) % 4;
                
                errortext += "Booklet binding requires you add pages in multiples of 4. ";
                addedpages = 1;
            }
            
            if (addedpages == 1) errortext += "Additional blank pages (not counted in design fee) are added to the book. ";
			
			break;
	}




	totalbook = colorpagesbook + bwpagesbook + bindingbook + ((designfee / quantity) + 0.005) + adpagepricetotal + blankpagesbookcost + printfee;
	total = (colorpagesbook + bwpagesbook + bindingbook + adpagepricetotal + blankpagesbookcost + printfee) * quantity + designfee;




	
	// Start setting values

	setDollarText('yc.designtotal', designfee);
	setDollarText('yc.designbook', (designfee / quantity + 0.005));
	
	setDollarText('yc.printfeetotal', (printfee * quantity));
	setDollarText('yc.printfeebook', printfee);
	
	setText('yc.pagecount', pagecountcontent + ' content / ' + pagecount + ' total');
	setText('yc.designtext', '(based on ' + pagecountcontent + ' pages)');
	
	
	setDollarText('yc.colorpagesbook', colorpagesbook);
	setDollarText('yc.colorpagestotal', colorpagesbook * quantity);
	setDollarText('yc.bwpagesbook', bwpagesbook);
	setDollarText('yc.bwpagestotal', bwpagesbook * quantity);
	setDollarText('yc.bindingbook', bindingbook);
	setDollarText('yc.bindingtotal', bindingbook * quantity);
	
	
	setText('yc.adpagecount', adpagescolor + ' color, ' + adpagesbw + ' B&amp;W');
	setDollarText('yc.adpagestotal', adpagepricetotal * quantity);
	setDollarText('yc.adpagesbook', adpagepricetotal);
	setDollarText('yc.adrevenuetotal', bookadrevenuetotal * quantity);
	setDollarText('yc.adrevenuebook', bookadrevenuetotal);
	
    
	setText('yc.blankpagecount', blankpagesbook + ' pages');
	setDollarText('yc.blankpagestotal', blankpagesbookcost * quantity);
	setDollarText('yc.blankpagesbook', blankpagesbookcost);
	
    
	setDollarText('yc.total', total);
	setDollarText('yc.totalbook', totalbook);
	
	setDollarText('yc.adjtotal', total - (bookadrevenuetotal  * quantity));
	setDollarText('yc.adjtotalbook', totalbook - bookadrevenuetotal);

	
	

	
	// Display ad section values
	for (i = 0; i < count; i++) {
		setDollarText('yc.salesbook' + i, bookadprofit[i]);
		setDollarText('yc.adpagesbook' + i, adpagesrequired[i]);
	}

	for (i = 0; i < count; i++) {
		document.getElementById('yc.piecespage' + i).value = piecesperpage[i];		
		document.getElementById('yc.price' + i).value = priceperpiece[i];		
		document.getElementById('yc.sales' + i).value = adsales[i];
        
        setText('yc.adpagesbook' + i, adpagesrequired[i]);
	}
	
	
	
	// Reset values displayed so the user sees what we do
	document.getElementById('yc.quantity').value = quantity;
	document.getElementById('yc.colorpages').value = colorpages;
	document.getElementById('yc.bwpages').value = bwpages;
	    
	document.getElementById('yc.binding').selectedIndex = bindingtype;		
	

	if (errortext != '') {
		setText('calcerrortext', '<strong>Problems:</strong> ' + errortext);
		document.getElementById('calcerrortext').style.visibility = 'visible';
	} else {
		setText('calcerrortext', errortext);
		document.getElementById('calcerrortext').style.visibility = 'hidden';
	}
        
    var hashvalue = '';
        
    hashvalue += 'quantity=' + quantity;
    hashvalue += '&';
    hashvalue += 'colorpages=' + colorpages;
    hashvalue += '&';
    hashvalue += 'bwpages=' + bwpages;
    hashvalue += '&';
    hashvalue += 'bindingtype=' + bindingtype;

	for (i = 0; i < count; i++) {
        hashvalue += '&';
        hashvalue += 'piecesperpage' + i + '=' + piecesperpage[i];
        hashvalue += '&';
        hashvalue += 'priceperpiece' + i + '=' + priceperpiece[i];
        hashvalue += '&';
        hashvalue += 'adsales' + i + '=' + adsales[i];
        hashvalue += '&';
        hashvalue += 'adprinttype' + i + '=' + adprinttype[i];
	}
    
    document.location.hash = hashvalue;    
}

function showErrorInLabel(id, show) {
	if (show) document.getElementById(id).className = 'inputerror label';
	else  document.getElementById(id).className = 'label';
}

function setDollarText(id, text) {
	setText(id, '$' + addCommas(text));
}

function setText(id, text) {
	/*
	if (document.body.textContent) {
    	document.getElementById(id).textContent = text;
	} else{
		document.getElementById(id).innerText = text;
	}
	*/
	document.getElementById(id).innerHTML = text;
}

function addCommas(nStr) {
	nStr = nStr.toFixed(2);
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}







