//=WW=======================================================
// CheckEmail(obj, classname)
// Basic email validation check, uses timer so it can be 'live'
// Usage: onkeyup=CheckEmail('id_of_inputbox', 'bademail')
//
// inputid		- inputbox element ID
// classname	- classname to add to inputbox if email invalid
//==========================================================
function CheckEmail(inputid, classname) {
	if(checktimer > 0) window.clearTimeout(checktimer);
	checktimer = window.setTimeout('CheckEmail_Callback("'+inputid+'", "'+classname+'")', 1000);
}
function CheckEmail_Callback(inputid, classname) {
	obj = document.getElementById(inputid);
	if(obj.value.length == 0) {
		if(typeof classname !== undefined)
   			obj.removeClass(classname);
   		return true;
	}
	var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(obj.value) == false) {
		if(typeof classname !== undefined)
			obj.addClass(classname);
		return false;
	} else {
		if(typeof classname !== undefined)
   			obj.removeClass(classname);
   		return true;
	}
}

//=WW=======================================================
// CreateElement(data)
// Creates a DOM element by passing an object with all 
// the information you want for the element in it.
// To avoid memory leaks in IE, pass one field as parent with a
// string identifying the ID of the parent DOM element to add to
//
// e.g. to create a tr with a class of 'header'
//		tr = CreateElement({tagtype: 'tr', className: 'header'});
//
// or to create a div with text inside
//		div = CreateElement({tagtype: 'div', text: 'Some text'});
//
// or to create a div containing two images
//		div = CreateElement(tagtype: 'div', children: 
//			[{tagtype: 'img', src: 'image1.jpg'}, {tagtype: 'img', src: 'image2.jpg'}]);
//
// Function returns the element to be used in an append
// e.g. table.appendChild(tr);
//==========================================================
function CreateElement(data)
{
	var e = document.createElement(data.tagtype);
	if(data.tagtype == 'input') e.type = (data.type == undefined ? 'text' : data.type);
	if(typeof data.parent == 'string') data.parent = document.getElementById(data.parent);
	if(data.parent != undefined) data.parent.appendChild(e);
	for(var key in data)
		if(key == 'style') for(var s in data.style) eval('e.style.'+s+' = data.style.'+s);
		else if(key == 'text') e.appendChild(document.createTextNode(data.text));
		else if(key == 'children') for(var i=0;i<data.children.length;i++) {data.children[i].parent = e; CreateElement(data.children[i]);}
		else if(key.substr(0,2) == 'on') eval('e.'+key+' = new Function("'+eval('data.'+key).replace(/\"/g, '\\"')+'")');
		else if(key != 'parent') eval('e.'+key+' = data.'+key);
	if(data.parent == undefined) return e;
}	

//=WW=======================================================
// IsValidDate(date, direction)
// Attempts to validate a date. Depending on the date, can 
// take into account dd/mm or mm/dd. Will also accept 2 or 4
// year dates and the use of - or / as the separator.
// Can also check if the date is before/after today.
//
// date			- string to validate
// direction	- optional. if specified will check if the date
//					is before or after today. Specify -1 for
//					before today, 1 for after today.
//
// Returns false if invalid or yyyy-mm-dd if valid.
//==========================================================
function IsValidDate(date, direction) {
	while(date.indexOf('-') > -1) date = date.replace('-', '/');
	while(date.indexOf(' ') > -1) date = date.replace(' ', '');
	date = date.split('/');
	
	if(date.length != 3) return false;
		
	if(isNaN(date[0]) || isNaN(date[1]) || isNaN(date[2])) return false;
		
	date[0] = parseInt(date[0]); date[1] = parseInt(date[1]); date[2] = parseInt(date[2]);
	
	if(date[0] < 1 || date[1] < 1 || date[2] < 1) return false;
	
	if(date[2].toString().length <= 2 && date[2] < parseInt(new Date("yy"))) date[2] = 2000 + date[2];
	else if (date[2].toString().length <= 2) date[2] = 1900 + date[2];
	
	if(date[1] > 12 && date[0] <= 12) {
		t = date[1];
		date[1] = date[0];
		date[0] = t;	
	}
	
	daysinmonths = new Array(31,(((date[2] % 4 == 0) && ( (!(date[2] % 100 == 0)) || (date[2] % 400 == 0))) ? 29 : 28 ),31,30,31,30,31,31,30,31,30,31);
	if(date[1] > 12 || date[0] > daysinmonths[date[1]-1]) return false;
	
	if(date[0].toString().length == 1) date[0] = '0' + date[0].toString()
	if(date[1].toString().length == 1) date[1] = '0' + date[1].toString()
		
	date = date[2] + '-' + date[1] + '-' + date[0];
	
	real_date = new Date(date.replace('-', '/').replace('-', '/'))
	now = new Date();
		
	if(direction == -1) if(real_date > now) return false;
	else if (direction == 1) if(real_date < now) return false;
	
	return date;
}

//=WW=======================================================
// CheckUsername(args)
// Validates a username against a database via AJAX
//==========================================================
function CheckUsername(args) {
	var scripturl = rooturl+'webapp/framework/includes/CheckUsername.php';
	args.input = typeof args.inputid == 'string' ? $(args.inputid) : args.input;
	args.scripturl = typeof args.scripturl == 'undefined' ? scripturl : args.scripturl;
	if(args.input.value == args.defaultvalue) {
		$(args.nomatchelement) !== null ? $(args.nomatchelement).style.display = 'none' : null;
		$(args.matchelement)   !== null ? $(args.matchelement).style.display   = 'none' : null;
		if(typeof args.matchclassname   !== 'undefined') args.input.removeClass(args.matchclassname);
		if(typeof args.nomatchclassname !== 'undefined') args.input.removeClass(args.nomatchclassname);
	} else {		
		new Ajax(args.scripturl, {method: 'post', 
			postBody: 'type='+args.type+'&username='+args.input.value, 
			onSuccess: function(t) {
			if(t.indexOf('exists') > -1) {
				$(args.nomatchelement) !== null ? $(args.nomatchelement).style.display = 'none' : null;
				$(args.matchelement)   !== null ? $(args.matchelement).style.display   = ''     : null;
				if(typeof args.matchclassname   !== 'undefined') args.input.addClass(args.matchclassname);
				if(typeof args.nomatchclassname !== 'undefined') args.input.removeClass(args.nomatchclassname);
			} else if(t.indexOf('unique') > -1) {
				$(args.nomatchelement) !== null ? $(args.nomatchelement).style.display = ''     : null;
				$(args.matchelement)   !== null ? $(args.matchelement).style.display   = 'none' : null;
				if(typeof args.matchclassname   !== 'undefined') args.input.removeClass(args.matchclassname);
				if(typeof args.nomatchclassname !== 'undefined') args.input.addClass(args.nomatchclassname);
			} else {
				$(args.nomatchelement) !== null ? $(args.nomatchelement).style.display = 'none' : null;
				$(args.matchelement)   !== null ? $(args.matchelement).style.display   = 'none' : null;
				if(typeof args.matchclassname   !== 'undefined') args.input.removeClass(args.matchclassname);
				if(typeof args.nomatchclassname !== 'undefined') args.input.removeClass(args.nomatchclassname);
			}
			},
			onFailure: function(t) {
			$(args.nomatchelement) !== null ? $(args.nomatchelement).style.display = 'none' : null;
			$(args.matchelement)   !== null ? $(args.matchelement).style.display   = 'none' : null;
			if(typeof args.matchclassname   !== 'undefined') args.input.removeClass(args.matchclassname);
			if(typeof args.nomatchclassname !== 'undefined') args.input.removeClass(args.nomatchclassname);
		}}).request();
	}
}

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function SwapImage(img, status) {
	var src = img.src;
	if(status == 'on' && src.indexOf('_off.') > 0) {
		img.src = src.replace('_off.', '_on.');
	}else if (status == 'off' && src.indexOf('_on.') > 0){
		img.src = src.replace('_on.', '_off.');
	}
}

function jumpto(url){location = url;}

function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
	iReturnValue += oElement.offsetTop;
	oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

current_machine = 0;
total_machines = 0;
timer = 0;

function setScrollPos()
{
	if(current_machine > 0) {
		var machine = $($('pod_recent').getElementById('info').getElementById('machine'+current_machine))
		var scrollbtn = $($('pod_recent').getElementById('button'));
		var percent = scrollbtn.getStyle('top').toInt() / 141;
		machine.style.position = 'relative';
		machine.style.top = (0 - (Math.max(machine.clientHeight - 170,0) * percent)) + 'px';
	}
}

function ChangeMachine()
{
	clearTimeout(timer);
	$('viewnextlink').removeEvents('click');
	current_machine += 1;
	if(current_machine > total_machines) current_machine = 1;
	for(i = 1; i <= total_machines; i++) {
		if(i == current_machine) {
			$('machine' + i).style.display =  '';
			$('pod_recent').getElementsByTagName('a')[0].href = 'products/' + $('machine' + i).getElementsByTagName('span')[0].innerHTML;
			$('viewnextlink').addEvent('click', function(){ChangeMachine()});
		} else {
			$('machine' + i).style.display =  'none';
		}
	}
	timer = window.setTimeout('ChangeMachine()', 20000);
}

dragging = false;

function stopDrag(){dragging = false;}

function SetupNav()
{
	var links;
	
	if($('navbar')) {
		var navbar = $('navbar');
		links = navbar.getElementsByTagName('a');
		
		var src = ''
		var images = new Array(links.length - 1);
		
		for(var i=0; i<links.length;i++) {
			$(links[i].getElementsByTagName('img')[0]).addEvent('mouseover', SwapImage.create({'arguments': [$(links[i].getElementsByTagName('img')[0]), 'on']}));
			$(links[i].getElementsByTagName('img')[0]).addEvent('mouseout', SwapImage.create({'arguments': [$(links[i].getElementsByTagName('img')[0]), 'off']}));
			src = $(links[i].getElementsByTagName('img')[0]).src
			src = src.replace('_off.', '_on.');
			images[i] = new Image();
			images[i].src = src;
		}
	}
	
	if($('pod_range')) {
		links = $('pod_range').getElementsByTagName('li');
		for(var i=0; i<links.length;i++) {
			$(links[i]).addEvent('mouseover', SwapImage.create({'arguments': [$(links[i].getElementsByTagName('img')[0]), 'on']}));
			$(links[i]).addEvent('mouseout', SwapImage.create({'arguments': [$(links[i].getElementsByTagName('img')[0]), 'off']}));				
			$(links[i]).addEvent('click', jumpto.create({'arguments': links[i].getElementsByTagName('a')[0].href}));
			links[i].style.cursor = 'pointer';
		}
	}
	
	if($('pod_buying')) {
		link = $('pod_buying').getElementsByTagName('a');
		link = link[0];
		$(link).addEvent('mouseover', SwapImage.create({'arguments': [$($('pod_buying').getElementsByTagName('img')[0]), 'off']}));
		$(link).addEvent('mouseout', SwapImage.create({'arguments': [$($('pod_buying').getElementsByTagName('img')[0]), 'on']}));				
	}
	
	if($('pod_recent')) {
		var scrollbtn = $($('pod_recent').getElementById('button'));
		scrollbtn.makeDraggable({container: 'scrollbar_buttonholder', modifiers: {x: null}, 
				onStart: function(){dragging=true;},
				onDrag: function(){
					dragging = true;
					setScrollPos();
				}, 
				onComplete: function(){window.setTimeout('stopDrag()', 500);}
			});
		$($('pod_recent').getElementById('scrollbar_buttonholder')).addEvent('click', function(e){
				if(dragging == false) {
					//var percent = e.clientY - getY(e.target) + 34; percent = percent / 174;
					//$($('pod_recent').getElementById('button')).style.top = (141*percent) + 'px';
					//setScrollPos();
				}
			});
		new Ajax(rooturl+'webapp/modules/ajax/RecentMachines.php', {method: 'get', 
			postBody: '', 
			onSuccess: function(t) {
						var children = Json.evaluate(t).children;
						var infodiv = $($('pod_recent').getElementById('info'))	
						for(i=0;i<children.length;i++) {
							children[i].parent = infodiv;
							CreateElement(children[i]);
						}
						current_machine = 0;
						total_machines = children.length;
						$('pod_recent').getElementById('viewnext').getElementsByTagName('span')[0].innerHTML = total_machines;
						ChangeMachine();
			}}).request();
	}
	
	if(navigator.appVersion.indexOf('MSIE 6.0') > 0 && $('pod_main')) {
		$('pod_main').style.background = 'url()';
		$('pod_main').innerHTML = '<img src="'+rooturl+'webapp/templates/default/images/podheader.png" style="position: absolute; top:0; left: 0; z-index: 0" width="613" height="52" />' + $('pod_main').innerHTML;
	}
	
	if(navigator.appVersion.indexOf('MSIE 6.0') > 0 && $$('.pod_main')) {
		for(i=0; i < $$('.pod_main').length; i++) {
		$$('.pod_main')[i].style.background = 'url()';
		$$('.pod_main')[i].innerHTML = '<img src="'+rooturl+'webapp/templates/default/images/podheader.png" style="position: absolute; top:0; left: 0; z-index: 0" width="613" height="52" />' + $$('.pod_main')[i].innerHTML;
		}
	}
	
	if(navigator.appVersion.indexOf('MSIE 6.0') > 0 && $('pod_main_mini')) {
		$('pod_main_mini').style.background = 'url()';
		$('pod_main_mini').innerHTML = '<img src="'+rooturl+'webapp/templates/default/images/podheader_mini.png" style="position: absolute; top:186px; left: 185px; z-index: -1" width="428" height="52" />' + $('pod_main_mini').innerHTML;
	}
	
	if($('pod_featured')) {
		var descs = $('pod_featured').getElementsByClassName('product_desc');
		for(var i=0; i<descs.length; i++)
			shapeWrapper(descs[i], "12","6,0,0|18,0,1|30,0,75|42,0,88|54,0,89|66,0,90|78,0,91");
	}
	
	if($('sellform_page1') && $('heightpad')) {
		arrFX['sellform_page1'] = new Fx.Style($('sellform_page1'), 'opacity', {duration: 300} );
		arrFX['sellform_page3'] = new Fx.Style($('sellform_page3'), 'opacity', {duration: 300} );
		
		arrFX['heightpad'] = new Fx.Style($('heightpad'), 'height', {duration: 300} )
				
		curpage = 1;
		
		arrFX['heightpad'].start($('sellform_page1').clientHeight);	
	}
		
	
	if($('googlemap')) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("googlemap"));
        map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(53.63916, -1.52871), 13);
        map.openInfoWindow(map.getCenter(),
                   document.createTextNode("We are here!"));
      }
      
      e = $('googlemap');
      while(e.parentNode) {
        if(e.className && e.className.indexOf('nohtc') > -1) {
          skip = true;
          break;
        }
        e = e.parentNode;
      }
	}
}

function shapeWrapper(obj, lineHeight,Xs) {
	var out = '';
	Xvalues = Xs.split('|');
	for(i=0; i < Xvalues.length; i++) {
		parts = Xvalues[i].split(',');
		out += '<div style="float:left;clear:left;height:'+lineHeight+'px;width:'+ parts[1]+'px"></div>';
		out += '<div style="float:right;clear:right;height:'+lineHeight+'px;width:'+ parts[2]+'px"></div>';
	}
	obj.innerHTML = out + obj.innerHTML
}

curpage = 0;
arrFX = new Array();

function GoPage(d)
{
	
	if(d == -1 && curpage == 1)	return false;
	if(d == 1 && curpage == 3) return false;
	
	var oldpage = 'sellform_page'+curpage;
	var newpage = 'sellform_page'+(curpage + d);
	
	if(curpage + d == 2 && !$('sellform_page2')) {
		$('sellform_page_'+$('product_type').value.toLowerCase()).id = 'sellform_page'+(curpage + d);
		arrFX['sellform_page2'] = new Fx.Style($('sellform_page2'), 'opacity', {duration: 300} );
	} else if (curpage + d == 1 && curpage == 2) {
		$('sellform_page2').id = 'sellform_page_'+$('product_type').value.toLowerCase();
		arrFX['sellform_page2'] = new Fx.Style($('sellform_page_'+$('product_type').value.toLowerCase()), 'opacity', {duration: 300} );
	}
		
	$(newpage).setStyles({display:'block', opacity: 0});
	
	arrFX['heightpad'].start($(newpage).clientHeight);
	
	arrFX[newpage].start(1);
	arrFX[oldpage].start(0);
	
	curpage += d;
	
	return false;
}

t_img = '';
r_img = '';
ignore = 1;

function ContinuePreview()
{
	var w = 400; var h = t_img.height;
	
	if(h < 10) h = 275;

	var fx1 = new Fx.Styles($('img_large'), {duration: 500, transition: Fx.Transitions.linear});
	var fx2 = new Fx.Styles($('image_loading_btm'), {duration: 500, transition: Fx.Transitions.linear});
	var fx3 = new Fx.Styles($('image_loading_mid'), {duration: 500, transition: Fx.Transitions.linear});
	var fx4 = new Fx.Styles($('image_loading'), {duration: 500, transition: Fx.Transitions.linear});
	
	fx1.start({'height': (h+26)});fx3.start({'height': h});fx2.start({'top': h+12});
	
	$('image_loading').src = t_img.src;
	
	fx4.start({'height': h, 'left': '20', 'top': '12', 'width': '400'});
	
	ignore = 1;
	$('image_loading').addEvent('mouseleave', function(){HideLarge()});
}

function ShowLarge(img)
{
	img.parentNode.style.position = 'relative';
	r_img = img;
	
	if($('img_large'))
		$('img_large').parentNode.removeChild($('img_large'));
		
	CreateElement({tagtype: 'div', id: 'img_large', style: {position: 'absolute', top: '-20px', left: '-20px', width: '440px', height: '150px', zIndex: '1000'}, parent: img.parentNode, onmouseout: 'HideLarge()', children: 
	[
		{tagtype: 'img', id: 'image_loading_top', src: rooturl + '/webapp/templates/default/images/image_loading_top.png', width: '440', height: '12', style: {position: 'absolute', top: '0', left: '0', zIndex: '1001'}},
		{tagtype: 'img', id: 'image_loading_mid', src: rooturl + '/webapp/templates/default/images/image_loading_mid.png', width: '440', height: '124', style: {position: 'absolute', top: '12px', left: '0', zIndex: '1002'}},
		{tagtype: 'img', id: 'image_loading_btm', src: rooturl + '/webapp/templates/default/images/image_loading_btm.png', width: '440', height: '14', style: {position: 'absolute', top: '136px', left: '0', zIndex: '1003'}},
		{tagtype: 'img', id: 'image_loading', src: rooturl + '/webapp/templates/default/images/image_loading.gif', width: '16', height: '16', style: {position: 'relative', top: '67px', left: '212px', zIndex: '1004'}}
	]});
		
		
	var file = img.src;
	file = file.replace('_small.png', '_large.jpg');
	t_img = new Image();
	t_img.onload = ContinuePreview;
	t_img.src = file;
}

function HideLarge()
{
	if(ignore == 0) {
		var fx1 = new Fx.Styles($('img_large'), {duration: 500, transition: Fx.Transitions.linear});
		var fx2 = new Fx.Styles($('image_loading_btm'), {duration: 500, transition: Fx.Transitions.linear});
		var fx3 = new Fx.Styles($('image_loading_mid'), {duration: 500, transition: Fx.Transitions.linear});
		var fx4 = new Fx.Styles($('image_loading'), {duration: 500, transition: Fx.Transitions.linear});
		
		fx1.start({'opacity': '0'});

	}
	ignore = 0;
}