// JavaScript Document

var ajax = new Array();
var images = new Array(
					   '/images/window/bikes.jpg',
					   '/images/window/close.png',
					   '/images/window/purple_background.png',
					   '/images/general/loading_1.gif',
					   '/images/general/PageNotFound.png',
					   '/images/general/photo.png',
					   '/images/tooltip/tt_arrow.png',
					   '/images/tooltip/tt_arrow_down.png',
					   '/images/icons/view_bike.png'
					   )





//***************************************************
//          Preload Images
//***************************************************
function preloadImages(images) {
	var imgSrc = '';
	if (document.images) {
		for (i=0; i < images.length; i++) {
			imgSrc = images[i];
			images[i] = new Image(); 
			images[i].src = imgSrc;
		}
	}
}
preloadImages(images);

//***************************************************
//          Hide & Show text in textboxes
//***************************************************
function clickIn(ref,sting) {
	if(ref.value == sting) {
		ref.value = '';
	}
}
function clickOut(ref,sting) {
	if(ref.value == '') {
		ref.value = sting;
	}
}


//***************************************************
// Get object
//***************************************************
function object(id) {
	return document.getElementById(id);
}



//***************************************************
//               SHOW AND HIDE DIV's
//***************************************************
function hideDiv(ref) {
	ref.style.display = 'none';
}
function showDiv(ref) {
	ref.style.display = 'inline';
};


//***************************************************
//               POPUP WINDOW
//***************************************************
function popwindow(url, name, x, y, height, width) {
	window.open( url, 'mywindow', "status = 1, height = "+height+", width = "+width+", top = "+y+", left = "+x+", resizable = 1, scrollbars=yes" );
	//window.open(url,'mywindow','width=400,height=200');
};



//***************************************************
//               SELECT OPTION
//***************************************************

function selectValue(id, val) {
	var obj = document.getElementById(id);
	var i;
	for (i=0; i < obj.options.length; i++) {
		if (obj.options[i].value == val) {
			obj.selectedIndex = i;
			break;
		}
	}
};

//***************************************************
//                   TEST EMAIL
//***************************************************

function isValidEmail(str) {
   //return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	if (str == "") {
		return false;	
	}
   
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	return (filter.test(str));
	

};


function isMouseLeaveOrEnter(e, handler) { if (e.type != 'mouseout' && e.type != 'mouseover') return false; var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; while (reltg && reltg != handler) reltg = reltg.parentNode; return (reltg != handler); }



// change the style of an element
function changeStyle(styleref, obj) {
	obj.className = styleref;
}


// Set form elements to good, warning or bad
function setGood(id) {
	obj = document.getElementById(id);
	if (obj.type == 'text' || obj.type == 'password') {
		changeStyle('good', obj);
	} else {
		changeStyle('formalert-good', document.getElementById('formalert-'+id));
		changeStyle('', obj);
	}
}
function setWarning(id) {
	obj = document.getElementById(id);
	if (obj.type == 'text' || obj.type == 'password') {
		changeStyle('warning', obj);
	} else {
		changeStyle('formalert-warning', document.getElementById('formalert-'+id));
	}
}
function setBad(id) {
	obj = document.getElementById(id);
	changeStyle('bad', obj);
}



function setBadSimple(id) {
	obj = document.getElementById(id);
	changeStyle('bad-simple', obj);
}

function setGoodSimple(id) {
	obj = document.getElementById(id);
	changeStyle('good-simple', obj);
}



/*
function setBad(id) {
	obj = document.getElementById(id);
	if (obj.type == 'text') {
		changeStyle('bad', obj);
	} else {
		changeStyle('formalert-bad', document.getElementById('formalert-'+id));
	}
}
*/



function getObjPosition(id) {
	
	var coords =  new Object();
	
    coords.x = 0;
    coords.y = 0;

        targetElement = document.getElementById(id);
        if(targetElement.x && targetElement.y) {
            coords.x = targetElement.x;
            coords.y = targetElement.y;
        } else {
            if(targetElement.offsetParent) {
                coords.x += targetElement.offsetLeft;
                coords.y += targetElement.offsetTop;
                while(targetElement = targetElement.offsetParent) {
                    coords.x += targetElement.offsetLeft;
                    coords.y += targetElement.offsetTop;
                }
            } else {
                //alert("Could not find any reference for coordinate positioning.");
            }
        }

	return coords;
	
};



// Disable Form Object
function disableFormObject(ID) {
	object(ID).disabled = true;	
}
// enable Form Object
function enableFormObject(ID) {
	object(ID).disabled = false;	
}


//***************************************************
// Hide div though slide
//***************************************************
var hDelay;			// delay timeout handler
var stepSize = 4;	// size of hide intervals
var speed = 2;		// speed of shrink: ms
var slideObj;		// slide object handler
var ease = 2;		// anamation ease
	
function slide(id,delay) {
	slideObj = object(id);
	hDelay = setTimeout("slideDiv()",delay);
}
	
function slideDiv() {
	var divHeight = parseInt(slideObj.offsetHeight);
	if (divHeight > 0) {
		slideObj.style.height = slideObj.offsetHeight - stepSize + 'px';
		hDelay = setTimeout("slideDiv()",speed);
		speed = speed + ease;
	} else {
		clearInterval(hDelay);
	}
}







// insert div after div
function insertafter(newChild, refChild) { 
	refChild.parentNode.insertBefore(newChild,refChild.nextSibling); 
}

// get elements by class name
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i < arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

// tooltip
//window.onload=function(){init_tt();}
addOnloadEvent(init_tt);

function init_tt() {

	var elements = new Array();
	elements1 = getElementsByClassName(document, 'div', 'tt');
	elements2 = getElementsByClassName(document, 'div', 'tt-help');
	
	elements = elements1.concat(elements2);

	for (i=0;i < elements.length;i++) {
		var contentObj = object(elements[i].id+'_c');
		var ttObj = object(elements[i].id);

		// Find tool tips screen quarter position
		var size = windowSize();
		var pos = findPos(ttObj);
		
		// Set class for balloon
		contentObj.className = 'ttballoon';
		
		//alert(pos.top+' : '+size.height/2);
		
		// Is tool tip on top or bottom of page
		if (pos.top+300 < size.height) {
			contentObj.innerHTML = '<div class="ttheader-b" id="header_'+i+'"></div><div class="ttbody"><div class="pad-10px">'+contentObj.innerHTML+'</div></div>';
		} else {
			contentObj.innerHTML = '<div class="ttbody"><div class="pad-10px">'+contentObj.innerHTML+'</div></div><div class="ttheader-t" id="header_'+i+'"></div>';
			contentObj.style.bottom = ttObj.offsetHeight+contentObj.offsetHeight+'px';
		}
		
		addEvent(ttObj, 'mouseover', showtt, true);
		addEvent(ttObj, 'mouseout', hidett, true);
		
		// Is tool tip on right of page
		
		if (pos.left+400 > size.width) {
			contentObj.style.left = '-220px';
			var arrow = object('header_'+i);
			arrow.style.left = '210px';
		}
		
		
		
		
		

		

	}
}

function showtt() {
	object(this.id+'_c').style.display = 'block';
}
function hidett() {
	object(this.id+'_c').style.display = 'none';
}

// common 'e' (event handler)
function standardizeEvent(e){
	if (!e) var e = window.event;
	if (!e.target) e.target = e.srcElement;
	return e;
}

// standardize 'this' and 'e' rubish
function createHandlerFunction(obj, fn){
	var o = new Object;
	o.myObj = obj;
	o.calledFunc = fn;
	o.myFunc = function(e){ 
		var e = standardizeEvent(e);
	  	return o.calledFunc.call(o.myObj, e);
	}
	return o.myFunc;
}

// add listener event
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
    	obj.addEventListener(evType, createHandlerFunction(obj, fn), useCapture);
    	return true;
	} else if (obj.attachEvent){
    	var r = obj.attachEvent("on"+evType, createHandlerFunction(obj, fn));
    	return r;
  	} else {
    	//alert("Handler could not be attached");
  	}
}

function addOnloadEvent(fnc){
  	if ( typeof window.addEventListener != "undefined" )
    	window.addEventListener( "load", fnc, false );
  	else if ( typeof window.attachEvent != "undefined" ) {
    	window.attachEvent( "onload", fnc );
  	} else {
    	if ( window.onload != null ) {
      		var oldOnload = window.onload;
      		window.onload = function ( e ) {
        	oldOnload( e );
        	window[fnc]();
      	};
    } else
		window.onload = fnc;
  }
}


function sortAds(sortParam,getString) {
	if (sortParam != 0) {
		top.open('/search.php?NS&PAGE='+getString+'&SORT='+sortParam,'_self');
	}
}


function windowSize() {
	var myWidth = 0, myHeight = 0, obj = new Object;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
		obj.width = myWidth;
		obj.height = myHeight;
		return obj;
}


function findPos(obj) {
	var curleft = curtop = 0; pos = new Object;
	var size = new Object;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		pos.left = curleft;
		pos.top = curtop;
		return pos;
	}
}




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);
}


// Allow hover menu to work in versions of ie
sfHover = function() {
	
	if (object("menu") == null) return false;
	
	var sfEls = object("menu").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);








// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008-2009 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}



//=================================================================================================================//
// Find Current Scroll Height
//=================================================================================================================//
function scrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


//=================================================================================================================//
// Remove Element
//=================================================================================================================//
function removeElement(ref) {
	var oNodeToRemove = object(ref);
	oNodeToRemove.parentNode.removeChild(oNodeToRemove);
}


//=================================================================================================================//
// Window
//=================================================================================================================//
function createWindow(content) {
	
	// Find locations for windows
	var overlayPos = scrollTop();
	var windowPos = overlayPos + 200;

	// Remove window if it already exists on page
	if (object('window') != null) {
		removeElement('window');
	}
	
	// Create Overlay
	var divTag = document.createElement("div");
	divTag.id = "window_overlay";
	divTag.className ="black_overlay";
	divTag.style.top = overlayPos+"px";
	document.body.appendChild(divTag);
		
	// Create Window
	var divTag = document.createElement("div");
	divTag.id = "window";
	divTag.className ="window_holder";
	divTag.innerHTML = '<div class="window"><div class="pad-10px"><div class="window_close" onClick="closeWindow();"></div>'+content+'</div></div>';
	divTag.style.top = windowPos+"px";
	document.body.appendChild(divTag);

	openWindow();
}

function openWindow() {
	if (object('window_overlay') != null) object('window_overlay').style.display = 'block';
	if (object('window') != null) object('window').style.display = 'block';
}
function closeWindow() {
	fade('window_overlay',0.5);
	fade('window',1);
}

function createLoginWindow() {
	var content = '<div class="window_heading">Welcome to Sellyourbike.com.au!</div> <p>We\'re happy to see you again! Please login to continue.</p> <table width="100%" border="0" cellpadding="5" cellspacing="0"> <tr> <td width="229"><form name="LOGIN_FORM" id="LOGIN_FORM" method="post" action="https://www.sellyourbike.com.au/account-login.html"> <label for="USERNAME">Username/Email</label> <input name="USERNAME" id="USERNAME" type="text" size="30"> <label for="PASSWORD">Password</label> <input name="PASSWORD" id="PASSWORD" type="password" size="30"> <br> <input class="button" type="submit" name="LOGIN" id="LOGIN" value="Log Me In"> </form></td> </tr> <tr> <td align="right"><table width="79%" border="0" cellpadding="5" cellspacing="0"> <tr> <td width="28"><img src="images/icons/lock.png" width="25" height="26" alt="Password"></td> <td width="283"><h5>Have you forgotten your <a href="account-password.html">Password</a>?</h5></td> </tr> <tr> <td><img src="images/icons/register.png" width="28" height="27" alt="Register"></td> <td><h5>Don\'t have an account? <a href="register.html">Create one now</a>. It\'s easy!</h5></td> </tr> </table></td> </tr> </table>';
		
	createWindow(content);
}


function loadingWindow() {
	var content = '<div class="window_heading">Loading Bike Details...</div><p>This will only take a moment, promise!</p><div style="text-align:center;"><img src="/images/general/loading_1.gif" width="160" height="24" alt="Loading"></div>';
		
	createWindow(content);
}


function paymentWindow() {
	var content = '<div class="window_heading">Processing Payment...</div><p><strong>Important!</strong> While your transaction is being processed please do not navigate away from, or refresh, this page.</p><div style="text-align:center;"><img src="/images/general/loading_1.gif" width="160" height="24" alt="Loading"></div>';
		
	createWindow(content);
}


function errroWindow() {
	var content = '<div class="window_heading">Oops! There\'s an error...</div><table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td align="left"><img src="/images/general/PageNotFound.png" width="128" height="128" alt="ERROR!"></td><td align="left"><p>We have detected an error on this page. Please check that you have filled out all the mandatory fields and ensure that they have been entered correctly.</p></td></tr></table><input class="window_close_button" type="button" value="Close" onClick="closeWindow();">';
		
	createWindow(content);
	setTimeout("closeWindow()", 10000);
}


function photoWindow() {
	var content = '<div class="window_heading">Uploading Photo...</div><table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td><img src="/images/general/photo.png" width="128" height="128" alt="PHOTO"></td><td><p>This could take a while if your photo is large. Please do not refresh this page while the upload is in progress.</p></td></tr></table><div style="text-align:center;"><img src="/images/general/loading_1.gif" width="160" height="24" alt="Loading"></div>';
		
	createWindow(content);
}













//=================================================================================================================//
// Fade Window
//=================================================================================================================//
var  TimeToFade = 500.0;

function fade(eid, startOpacity) {
	var element = object(eid);
	if(element == null)
		return false;
	 
	element.FadeTimeLeft = TimeToFade*startOpacity;
	element.startOpacity = startOpacity;
	setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
}


function animateFade(lastTick, eid) {  
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
	var element = object(eid);
	
	if(element.FadeTimeLeft <= elapsedTicks) {

		if (element != null) element.style.display = 'none';

		element.style.opacity = element.startOpacity;
		element.style.filter = 'alpha(opacity = '+ Math.round(element.startOpacity*100) +')';
		
		return true;
	}

	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal =  element.FadeTimeLeft/TimeToFade;

	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
	setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}













