// JavaScript Document

//		Written by Mr Dougal for Smart Solutions group
//		Unless otherwise noted



function toggleElement(myHref){
	
	
	if(document.getElementById){
			var target = myHref.href;
			var targetId = target.substring(target.indexOf('?')+1,target.length);

			var myTarget = document.getElementById(targetId);
			//var myLink = document.getElementById('q'+ID);

		//alert(parent+" : "+this);
			
		if(myTarget.style.display == "none"){
			myTarget.style.display = "";
			myHref.className = "out";
		} else {
			myTarget.style.display = "none";
			myHref.className = "in";
		}
	}
}

function gotoJobLog(url){

var question = confirm("JobLog will open in a new window, additionally you need an account to access JobLog");

	if(question == true){
		var thewindow = window.open(url, '_blank');
		thewindow.focus();
		return thewindow;
	}
}

function viewPDF(url,features){

if(!features){
	var features = 'location=0,resizable=1,width=750,height=550';
}

var thewindow = window.open(url, '_blank',features);
thewindow.focus();
return thewindow;

}

function preloadImages(){

	//	This is for the images that are used on *:hover .css styles

var d=document; 
if(d.images){ 
	if(!d.MM_p) {
		d.MM_p=new Array();
	}

	var a = new Array();	
	var i,j=d.MM_p.length;
	a.push('/img/site/pdf-download-small-red.gif');
	
	for(i=0; i<a.length; i++){
		if (a[i].indexOf("#")!=0){ 
			d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
		}
	}
	}
}

function preFlightForm(myform){

	
	var errorMsg ='';
	var err = false;
	var errorCount = 0;
	
	//	Locate send button, and disable it
	var submitBtn = myform.send;
	submitBtn.disabled = true;
	submitBtn.className = '';
	
	for(var i=0; i < myform.length;i++){
		
		//	Check if field is required, or has been set in error
		if((myform[i].className =='required')||(myform[i].className =='required, error')){
			
			if((myform[i].value == null)||(myform[i].value == '')){
				
				if(!err){
					err = true;
					
					//	Establish the first field for selection
					var errFld = myform[i];
				}
				errorCount++;
				errorMsg += '- '+myform[i].name+"\n";
				myform[i].className = 'required, error';
				
			} else if(myform[i].className == 'required, error'){
				//	Reset to required, since no longer in error
				myform[i].className = 'required';
			}
			
		}
	}
	
	if(err){
		var msg;
		
		if(errorCount >1){
			msg = "The following fields need to be filled out\n";
			msg += errorMsg;
		}
		else{
			msg = errFld.name +" wasn't correctly filled out";
		}
		
		
		alert(msg);
		
		//	 Re-enable the send button
		submitBtn.disabled = false;
		submitBtn.className = 'submit';
		errFld.focus();
	}
	return !err;
	
}
function clearTextArea(area,msg){
	
	if(area.value === msg){
		area.value = "";
	}
}

//		FADE SCRIPT
// This technique is a combination of a technique I used for highlighting FAQ's using anchors 
// and the ever popular yellow-fade technique used by 37 Signals in Basecamp.

// Including this script in a page will automatically do two things when the page loads...
// 1. Highlight a target item from the URL (browser address bar) if one is present.
// 2. Setup all anchor tags with targets pointing to the current page to cause a fade on the target element when clicked.

var FadeInterval = 300;
var StartFadeAt = 5;

var FadeSteps = new Array();
	FadeSteps[1] = "#FEFFFF";
	FadeSteps[2] = "#FAFFFF";
	FadeSteps[3] = "#F5FFFE";
	FadeSteps[4] = "#F1FFFE";
	FadeSteps[5] = "#E9FFFD";
	FadeSteps[6] = "#E5FFFD";
	FadeSteps[7] = "#E0FFFC";

// These are the lines that "connect" the script to the page.
var W3CDOM = (document.createElement && document.getElementsByTagName);
addEvent(window, 'load', initFades);

// This function automatically connects the script to the page so that you do not need any inline script
// See http://www.scottandrew.com/weblog/articles/cbs-events for more information
function addEvent(obj, eventType,fn, useCapture)
{
	if (obj.addEventListener) {
		obj.addEventListener(eventType, fn, useCapture);
		return true;
	} else {
		if (obj.attachEvent) {
			var r = obj.attachEvent("on"+eventType, fn);
			return r;
		}
	}
}

// The function that initializes the fade and hooks the script into the page
function initFades()
{
	if (!W3CDOM) return;
    
// This section highlights targets from the URL (browser address bar)
    
    // Get the URL
    var currentURL = unescape(window.location);
    // If there is a '#' in the URL
    if (currentURL.indexOf('#')>-1) 
        // Highlight the target
        DoFade(StartFadeAt, currentURL.substring(currentURL.indexOf('#')+1,currentURL.length));
    

// This section searches the page body for anchors and adds onclick events so that their targets get highlighted
    
    // Get the list of all anchors in the body
    var anchors = document.body.getElementsByTagName('a');

    // For each of those anchors
    for (var i=0;i<anchors.length;i++)

        // If there is a '#' in the anchors href
        if (anchors[i].href.indexOf('#')>-1)

            // Add an onclick event that calls the highlight function for the target
            anchors[i].onclick = function(){Highlight(this.href);return true};
}

// This function is just a small wrapper to use for the oncick events of the anchors
function Highlight(target) {

	// Get the target ID from the string that was passed to the function
    var targetId = target.substring(target.indexOf('#')+1,target.length);
    DoFade(StartFadeAt, targetId);
}

// This is the recursive function call that actually performs the fade
function DoFade(colorId, targetId) {
    if (colorId >= 1) {
		document.getElementById(targetId).style.backgroundColor = FadeSteps[colorId];

        // If it's the last color, set it to transparent
        if (colorId==1) {
            document.getElementById(targetId).style.backgroundColor = "transparent";
		}
        colorId--;
		
        // Wait a little bit and fade another shade
        setTimeout("DoFade("+colorId+",'"+targetId+"')", FadeInterval);
	}
}

// END OF THE FADE SCRIPTS

//	Slideshow
	


function showSlide (slideName)
	{
		var myObj = document.getElementById(slideName);
		myObj.parentNode.scrollTop = myObj.offsetTop;
		//Effect.DivSlideTo(slideName,{duration:2})
	}
		
var currentObject = '';


//	Start of the fancy show and hide

function myToggle (myHref,myTarget)
{
	// body...

	  if (currentObject != myHref.href) {
		
		myHref.className = 'out';
		
		//	Roll the blind up
		new Effect[Element.visible(myTarget),'BlindUp'](myTarget, {
			duration: 1,
			afterFinishInternal: function(){
			
			document.getElementById(myTarget).innerHTML = "loading";
				new Ajax.Updater(myTarget, myHref.href, {
					method: 'get',
					
					onFailure: function(){ Element.classNames(myTarget).add('failure')},
					onComplete: function(){
						new Effect['BlindDown'](myTarget, {duration: 1});
						currentObject = myHref.href;
					}
				}
			
			);
			}});
		}else{
			new Effect[Element.visible(myTarget) ? 
		    'BlindUp' : 'BlindDown'](myTarget, {duration: 1});
		}
}

// For the demo calculator
function setModule(myInput,t){
	
	var tt = document.getElementById(t);
	
	if(myInput.checked){
		tt.className = 'active';
	}else{
		tt.className = 'hidden';
	}
	addModuleCount(myInput);
}

function setTrafficUsage(myInput){
	
	/*var warn = document.getElementById('trafficWarning');
		warn.innerHTML = '<span id="trafficPenalty"></span>';
	*/
	if(isNaN(myInput.value)){
		myInput.value = "1000";
	}
	
	if(myInput.value > 1000){
		
		var excess = Math.ceil(myInput.value - 1000);
		myInput.form.elements['varExcessTraffic']
		//warn.innerHTML = '$<span id="trafficPenalty">'+(excess*.1)+'</span> for excess traffic';
		//alert('setTrafficUsage '+(excess/10));
	}
	
	calTotalCost();
	
	
}

function setDiscUsage(myInput){
	
	warn = document.getElementById('discWarning');
	warn.innerHTML = '<span id="discPenalty"></span>';
	
	if(isNaN(myInput.value)){
		myInput.value = "10";
	}
	
	if(myInput.value > 10){
		var excess = Math.ceil(myInput.value - 10);
		warn.innerHTML = '$<span id="discPenalty">'+(excess*5)+'</span> for excess disc usage';
	}
	
	calTotalCost();
}

function setUserCount(myInput){
	
	if(isNaN(myInput.value)){
		//alert("Please enter a number");
		myInput.value = document.getElementById('room').childNodes.length;
		myInput.focus();
	}else{
		//alert("changed");
		//updateTotals(myInput,'');
		var valueCeil = Math.ceil(myInput.value);
		
		if(valueCeil > 1){
			addUsers(valueCeil);

		}else{
			addUsers(1);
			myInput.value = 1;
		}
		
		addTotals(myInput);
		calTotalCost();
				//doUpdate(myInput);
		//updateGrandTotal(myInput.form);
	}
	
}

function addUsers(val){
	
	var room = document.getElementById('room');
	var user1 = document.getElementById('user1');
		
	if(val > room.childNodes.length){
		//	need to add some little guys into the room
		
		for(var roomCount = room.childNodes.length; roomCount < val; roomCount++){ 
			var user = document.createElement('img');
			user.setAttribute('src',user1.src);
			user.setAttribute('id','user'+(roomCount+1));
			room.appendChild(user);
		}
	}else{
		// need to remove items
		
		for(var roomCount = room.childNodes.length; roomCount > val; roomCount--){
			var removeme = document.getElementById('user'+roomCount);
			room.removeChild(removeme);
		}
	}
	
}
function addTotals(myInput){
	
	document.getElementById('userCount').innerHTML = myInput.value;
	document.getElementById('userCostTotal').innerHTML = formatCurrency(myInput.value*document.getElementById('userPerMonthCost').innerHTML);
}

function addModuleCount(myInput){
	
		var totalModules = 0;

	for(var i=0;myInput.form.elements.length > i;i++){
		
		if(myInput.form.elements[i].checked){
			totalModules += 1;
		}
	}
	document.getElementById('numModules').innerHTML = totalModules;
	calTotalCost();
}
function calTotalCost(){
	var totalModules = Number(document.getElementById('numModules').innerHTML);
	var userCount =  document.getElementById('userCount').innerHTML;
	var userCostPerMonth = Number(document.getElementById('userPerMonthCost').innerHTML);
	var traffic = Number(document.getElementById('trafficPenalty').innerHTML);
	var disc = Number(document.getElementById('discPenalty').innerHTML);
	
	
	
	var totalUserCost = (Number(userCount)*userCostPerMonth);
	var subTotal = (totalModules*totalUserCost)+traffic+disc;
	document.getElementById('grandTotal').innerHTML = formatCurrency(subTotal);
}
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

//window.onload = preloadImages