
var fade_speed = 600;
//var startplay = 4000;

$(function(){
	$('#slides').slides({
		preload				: 	true,
		generatePagination	:	false,
		slideSpeed			: 	1000,
		play				: 	5000,
		pause				: 	2000
	});
});

//var smbackground;

$(function(){
	$('#slides_sm').slides({
		preload				: 	true,
		generatePagination	:	false,
		effect				: 	'fade',
		crossfade			: 	true,
		fadeSpeed 			: 	1000,
		play				: 	5000,
		animationStart		:	function() {
			//$("div.slides_container").css('background-image', smbackground);
		},
		animationComplete	:	function(current) {
			//smbackground = $("#ban_sm_"+current).css('background-image');
		}
	});
});

(function($) {
    $.fn.customFadeIn = function(speed, callback) {
        $(this).fadeIn(speed, function() {
                if(jQuery.browser.msie)
                        $(this).get(0).style.removeAttribute('filter');
                if(callback != undefined)
                        callback();
        });
    };
    $.fn.customFadeOut = function(speed, callback) {
        $(this).fadeOut(speed, function() {
                if(jQuery.browser.msie)
                        $(this).get(0).style.removeAttribute('filter');
                if(callback != undefined)
                        callback();
        });
    };
})(jQuery);

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

function idevice(rotate) {
	rotate = typeof(rotate) != 'undefined' ? rotate : window.innerHeight;
	//alert(rotate);
	if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
		$("#footer").css("position", "static").css('bottom', '0px');
		$("#footer").css("visibility", "hidden");
		var counter = 0;
		if ($('#the_iframe').length) {
			$("#the_iframe").load( function() {
				if(counter > 0) { return; }
				if (document.height <= 1131 && window.innerHeight > 600) {
					var iheight = document.height-70;
				} else if (document.height <= 1131 && window.innerHeight < 600) {
					var iheight = 1050;
				} else {
					var iheight = document.height-40;
				}
				$("#footer").css({position : "absolute", visibility : "visible", top : iheight+"px"});
				counter++;
			});
		} else {
			var boost = 0;
			var move = 0;
			var winheight = rotate;
			var docheight = document.height;
			if (docheight < 550) { boost = 170; }
			if (docheight-40 < winheight) { move = 70; }
			iheight = docheight-move+boost;
			//alert(docheight-40+'!  -  '+(winheight)+'!');
			$("#footer").css({position : "absolute", visibility : "visible", top : iheight+"px"});
		}
	}	
}

var rotationwidth = 0;
var portrait = window.innerHeight;

function irotate() {
	
	/*if (portrait = 0 && rotationwidth == 0 && window.innerHeight < 600) {
		rotationwidth = window.innerHeight;
		portrait = window.innerHeight;
	} else if (rotationwidth == 0) {
		rotationwidth = window.innerHeight;
	}*/
	
	if(typeof window.onorientationchange != 'undefined'){
		if ( orientation == 0 ) {
			 //Do Something In Portrait Mode
			 if (rotationwidth == 0) {
				 portrait = window.innerHeight;
			 }
			 rotationwidth = portrait;
		} else if ( orientation == 90 ) {
			 //Do Something In Landscape Mode
			 rotationwidth = window.innerHeight; 
		} else if ( orientation == -90 ) {
			 //Do Something In Landscape Mode
			 rotationwidth = window.innerHeight; 
		} else if ( orientation == 180 ) {
			 //Do Something In Landscape Mode
			 rotationwidth = window.innerHeight; 
		}
	}
	
	idevice(rotationwidth);

}

window.onorientationchange=irotate;
		
$(document).ready(function(){
	
	$('input, textarea').bind('keyup click blur focus change paste', function() {
	
		//$('.testarea').html($(this).val());
		
		var value = $(this).val();
		if (value.match(/[^a-z0-9()\/\'":\*+|,.; \- !?&#$@]/gi, '') && $(this).attr('type') != 'submit' && $(this).attr('type') != 'reset') {
			if ($(this).attr('name') == 'Email' || $(this).attr('name') == 'email') {
				$(this).val($(this).val().replace(/[^a-z0-9()\/\'":\*+|,.; \-_ !?&#$@]$/gi, ''));
			} else {
				$(this).val($(this).val().replace(/[^a-z0-9()\/\'":\*+|,.; \- !?&#$@]/gi, ''));
			}
		}
	
	});
	
	//smbackground = $("#ban_sm_1").css('background-image');
						   
	$('select').not('form[name="mainform"] select, #locbrandselect select').dropp();
	
	//var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	badBrowser = false;
	
	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod' || badBrowser) {
		 $("#footer").css("position", "static");
		 idevice();
	};
	
	function dropMenuAnim() {
		$('.backg').stop().animate({"marginTop": "4px"},{duration: fade_speed, easing:'easeOutQuad', complete: function() {
			//$('#msgbox').append(' CALLBACK!');																											
		}});	
		movecheck = 1;
		newCheck = 1;
	}
	
	var prev;
	
	var folder = "navigation/";
	var file;
	var content = new Array();
	var arLen = brands.length;
	
	// This loop is no longer used. 
	// I've kept it and commented out the necessary lines, just incase any variables were reused elsewhere.
	for ( var i=0, len=arLen; i<len; ++i ){
		file = folder + brands[i] + '.php';
		//content['brand_'+brands[i]] = getFile(file);
		var id = 'brand_'+brands[i];
		var brand = id.split("_");
		//$('#nav_'+brand[1]).html(content[id]);
	}

	var hoverCheck = 0;
	var delayCheck = 0;
	var brandCheck = 0;
	var hoverDelay = null;
	var movecheck = 1;
	var newCheck = 0;
	var dropmouse = 0;
	var brandmouse = 0;
	var absolute = 0;
	//$('#hover_box,#current,#previous,.nav_contain').stop().animate({opacity: 0}, 0);
	$('#current,#previous,.nav_contain').stop().animate({opacity: 0}, 0);
	$('#current,#previous').css('display', 'block');
	
	$('.insert').hover(function() {
		dropmouse = 1;
	}, function() {
		dropmouse = 0;
	});
	
	$('.brand_link').hover(function() {
		brandmouse = 1;
	}, function() {
		brandmouse = 0;
	});
	
	
	/**************** RANGE PAGE CLICK ********************/
	
	var oldclick = "";
	
	$('.modellink').bind('click', function(e) {
										   
		var loadingpage = '/pages/loading.html';
		
		$('#the_iframe').attr('src', loadingpage);
		
		oldclick = $(this).attr('href');
		
		$('.imgfade .title').html($(this).text());
		$('.imgfade img').attr('src', $(this).parent().children('img').attr('src'));
		$('.imgfade').fadeTo(0, 0).css('display', 'block').fadeTo(200, 1, function() {
			$('.img .title').html($('.imgfade .title').html());
			$('.img img').attr('src', $('.imgfade img').attr('src'));
			$('.imgfade').css('display', 'none');
		});
		
		$('#the_iframe').load(function() { 
			if ($(this).attr('src') == loadingpage) {
				$(this).attr('src', oldclick); 
			} else {
				$(this).unbind('load');
			}
			
		});
		
		idevice();
		
		e.preventDefault();
		//return false;
	});
	
	
	
	
	/************* ENEWS 'Select All' FUNCTION *****************/
	
	$("#SelectAll").click(function() {
		var checked_status = this.checked;
		$(":checkbox").not(this).each(function() {
			this.checked = checked_status;
		});
	});	
	
	
	/************* ENEWS 'Submit' FUNCTION *****************/
	
	$('#subForm').submit(function() {
		if ($("input[type=checkbox]").is(':checked')) {
		} else {
			alert('Please select at least one Manufacturer to subscribe to')
			return false;	
		}
	});
	
	
	/************** Hawthorn / Medindie Tabs *****************/
	
	var modelid = 17495;
	var oldid = 11917;
	
	$('.tabs a').click(function() {
		
		$('.tabs a').not(this).attr('class', 'deselected');
		$(this).attr('class', 'selected');
		
		$('a.modellink').each(function() {
			var alink = $(this).attr('href');
			alink = alink.replace("ID="+oldid, "ID="+modelid);
			$(this).attr('href', alink);
		});
		
		if (oldclick == "") {
			oldclick = $('#the_iframe').attr('src');
		}
		
		//alert(lastclick);
		
		var framelink = oldclick;
		framelink = framelink.replace("ID="+oldid, "ID="+modelid);
		$('#the_iframe').attr('src', framelink);
		
		var temp = oldid;
		oldid = modelid;
		modelid = temp;
								
	});
	
	
	
	/************* DROPDOWN NAVIGATION *****************/
	
	$('.brand_link').not('menu_list ul,#hover_box').click(function() { 
		$('.brand_link').not(this).not('#hover_box').stop().css('background-color', 'transparent').fadeTo(200, 0.5);
		$(this).not('#hover_box').stop().css('background-color', 'white').fadeTo(100, 1);												   
		dropMenuAnim(); 
	});
	
	$('.brand_link,#hover_box').not('menu_list ul').hover(function() {
		
		var id = $(this).attr('id');	
		var thisclass = $(this).attr('class');
		
		//$(".nav_contain").stop();
		
		//$('#spacey').append(' !OVER! ');
		
		if (id == 'hover_box' && absolute == 1) { falsestrike = 1; return; } else { falsestrike = 0; } 
		
		//$('#spacey').html(' !!RUNNING!! ');
		
		absolute = 0;
		
		if ((id != 'hover_box' && delayCheck != 0) || (id != 'hover_box' && newCheck == 1)) {
			//$('#textbox').html("HIT!!");
			//$('#textbox').html(id);
			$('.brand_link').not(this).not('#hover_box').stop().css('background-color', 'transparent').fadeTo(200, 0.5);
			$(this).not('#hover_box').stop().css('background-color', 'white').fadeTo(200, 1);	
		} else if (id != 'hover_box' && delayCheck == 0) {
			$('.brand_link').not(this).stop().css('background-color', 'transparent').fadeTo(100, 1);
			$(this).not('#hover_box').stop().css('background-color', 'white').fadeTo(100, 1);
		}
		
	
		if (brandCheck == 0 && thisclass == 'brand_link') {
			brandCheck = 1;
		} else {
			brandCheck = 0;	
		}
		
		if (dropmouse == 1) {
			//$('#msgbox').html("IN THE .insert MATRIX! | "+hoverCheck);
		}
			//$('#textbox').html('ID: '+id+'   HOVERCHECK: '+hoverCheck+'   DROPMOUSE: '+dropmouse);
		//$('#textbox').append('TRIGGER ON!<br />');
		if (id != 'hover_box' || (id == 'hover_box' && hoverCheck != null && newCheck == 1) || dropmouse == 1) {
				//$('#textbox').append('ID: '+id+'   HOVERCHECK: '+hoverCheck+'   DROPMOUSE: '+dropmouse+'<br />');
				if (hoverCheck != 0) { clearTimeout(hoverCheck); };
				if (id != 'hover_box') {
					
					//$('#spacey').append('NOW IN!');
					
					clearTimeout(hoverCheck);
					$('#hover_box').css('display', 'block');
					var brand = id.split("_");
					$('#hover_box').css('z-index', '99999');
					$('.nav_contain').css('z-index', '1');
					$('#nav_'+brand[1]).css('z-index', '10');
					//$('#hover_box').stop().animate({opacity: 1}, fade_speed);
					if (movecheck == 1) {
						
						movecheck = 0;
						if (newCheck == 0) {
							$('.backg').stop(true, false);
							clearTimeout(hoverCheck);
							clearTimeout(delayCheck);
							delayCheck = setTimeout(function() {
								//$('#msgbox').append(' DELAY!');
								$('.brand_link').not($('#'+id)).not('#hover_box').stop().css('background-color', 'transparent').fadeTo(200, 0.5);
								$($('#'+id)).not('#hover_box').stop().css('background-color', 'white').fadeTo(100, 1);
								//$('.brand_link').not($('#'+id)).not('#hover_box').fadeTo(200, 0.5);
								dropMenuAnim();
							}, 500);
						} else {
							$('.backg').stop().animate({"marginTop": "4px"},{duration: fade_speed, easing:'easeOutQuad', complete: function() {
								//CALLBACK IF NEEDED																												
							}});	
							movecheck = 1;
							newCheck = 1;
						}
					}
					if (dropmouse < 1) {
						$('#nav_'+brand[1]).stop().css('display', 'block').animate({opacity: 1}, fade_speed/6);
						$(".nav_contain:not(#nav_"+brand[1]+")").stop().animate({opacity: 0}, fade_speed/6, function() { $(this).css('display', 'none'); });
						prev = brand[1];
					}
				}
		}
	}, function() {
		//$('#textbox').append('TRIGGER OUT!<br />');
		
		var id = $(this).attr('id');
		
		//$('#spacey').append(absolute +'|'+ id);
		 if (id == 'hover_box' && falsestrike == 1) { return; } 
		
		var brand = id.split("_");
		clearTimeout(hoverCheck);
		if (brandCheck == 0) { clearTimeout(delayCheck); }
		brandCheck = 0;
		//$('#msgbox').html('HOVER OUT!');
		hoverCheck = setTimeout(function() { 
			$('.brand_link').stop().css('background-color', 'transparent').fadeTo(100, 1);
			brandCheck = 0;
			movecheck = 1;
			clearTimeout(delayCheck);
			delayCheck = 0;
			absolute = 1;
			$('.backg').stop().animate({"marginTop": "-374px"},{duration: fade_speed-10/2, easing:'easeOutQuad', complete: function() {
				//$('#spacey').append('NOW OUT');
				$(".nav_contain").stop().animate({opacity: 0}, 0);		
				$('#hover_box').css('z-index', '1');
				$('#hover_box').css('display', 'none');
				newCheck = 0;
				hoverCheck = null;
				absolute = 0;
				//$('#textbox').html('');
			}});
			
		}, 60);
		
	});
	
	
	$('.box_nav a').wrap('<div id="box_surround"></div>');
	
	$('.box_nav a').hover(function() {
		$(this).parent().removeClass('box_surround').addClass('new_box');
	}, function() {
		$(this).parent().removeClass('new_box').addClass('box_surround');
	});
	
	$('#menu_list li').children('ul').animate({opacity: 0}, 0);
	
	$('#menu_list li').hover(function() {
		$(this).children('ul').css('z-index', '200');
		$(this).children('ul').css('display', 'block');
		$(this).children('ul').animate({opacity: 1}, 200);				   
	}, function() {
		$(this).children('ul').animate({opacity: 0}, 200, function() {
			$(this).css('display', 'none');
		});
	});
	
	$('.controls div a').animate({opacity: 0}, 0).css('visibility', 'visible');
	$('.controls div a').hover(function() {
		$(this).stop().animate({opacity: 1}, 200);	   
	}, function() {
		$(this).stop().animate({opacity: 0}, 200);
	});
	
	// BOTTOM BUTTON HOVER
	$('.onecol a img').hover(function() {
		$(this).stop().animate({opacity: 0}, 300);	   
	}, function() {
		$(this).stop().animate({opacity: 1}, 300);
	});
	
	// MEET THE TEAM BOXES
	//$('.team .hidden, .locations .hidden').animate({opacity: 0}, 0).css('display', 'block');
	$('.team .hidden, .locations .hidden').css({'display' : 'block', 'visibility' : 'visible'}).animate({opacity: 0}, 0);
	
	var hoverTeam=0;
	
	
	$('.team .hidden, .locations .hidden').live( 'mouseover',  function() {
		$(this).parent().children('.hidden').each(function() {	
			hoverTeam = this;
			$(this).stop().animate({opacity: 0}, 250);
		});
	} ).live( 'mouseout', function() {
		$(this).parent().children('.hidden').each(function() {
			$(this).stop().animate({opacity: 0.4}, 250);
		});
	} );
	
	$('.opt').live( 'mouseover',  function() {
		var hoverBox = '';
		if (hoverTeam != 0) {
			hoverBox = hoverTeam;
		}
		$('.hidden').not(hoverBox).stop().animate({opacity: 0.4}, 250);						  
	} ).live( 'mouseout', function() {
		$('.hidden').stop().animate({opacity: 0}, 250);
		hoverTeam = 0;
	} );
	
	
	// MEET THE TEAM SELECTER
	$('#opt1, ').css('z-index', '999');
	$('#opt2').css('z-index', '1');
	$('#opt2').css('display', 'block')
	$('#opt2 .team, #opt2 .locations').each(function(index) {
		$(this).fadeOut(0);
	});

	var lastclick = 'opt1';
	
	$('#opt2').css('visibility', 'hidden');

	$('.opt1, .opt2').click(function() {
		if ($(this).attr('class') == 'opt1' && lastclick != 'opt1') {
			lastclick = 'opt1';
			var first = 'opt1';
			var second = 'opt2';
			var type = 'Sales';
		} else if($(this).attr('class') == 'opt2' && lastclick != 'opt2') {
			if ($('#opt1').parent().children('#opt2').length) {
				lastclick = 'opt2';
				var first = 'opt2';
				var second = 'opt1';
				var type = 'Service'; 
			} else {
				return;
			}
		}
		
		var count = $('#'+second+' .team, #'+second+' .locations').length;
		
		$('#'+second+' .team, #'+second+' .locations').each(function(index){
			$('#title').fadeOut(200, function() {
				$('#title_type').replaceWith('<span id="title_type">'+type+'</span>');
				$('#title').fadeIn(200);
			});
			$(this).delay(100*index).fadeOut(400, function() {
				if (!--count) {
					$('#'+second).css('visibility', 'hidden');
				};											  
			});
		});
		$('#'+second).css('z-index', '1');
		$('#'+first).css('z-index', '999');
		$('#'+first+' .team, #'+first+' .locations').delay(500).each(function(index){
			$('#'+first).css('visibility', 'visible');
			$(this).delay(100*index).fadeIn(400);
		});
	/********	********/
	});
	
	var brandlook = {};
	
	if ($('#brandselect').length) {
		var tempval = $('#brandselect').attr('value');
		brandlook[tempval.toUpperCase()] = 'set';
	} else {
		brandlook[0] = "";
	}
	
	fancyfunction(".team .hidden a");
	
	//Move the hidden menu for drop down
	var newmar = '-'+$('#location_links').outerHeight()+'px';
	var marval = $('#location_links').outerHeight();
	$('#location_links').css({'margin-top': newmar, 'display': 'block'});
	
	var defaultSpeed = 400;
	var animationSpeed = defaultSpeed;
	
	//Shows the menu	
	function showLocationDrop(e) {
									   
		if ($('#location_links').css('margin-top') != '0px') {
			$(document).bind('click', function(e) { 
				if (e.target.id != 'location_links' && e.which == 1) {
					$('#location_links').stop().animate({'margin-top': newmar}, 200, function() { $('.drop_select a').css('background', 'none'); }); 
					$(document).unbind('click');
				}
			});
			$('.drop_select a').css('background', '#666666');
			$('#location_links').stop().animate({'margin-top': '0px'}, animationSpeed); 
			if (animationSpeed == 0) { animationSpeed = defaultSpeed; }
		} else {
			$('#location_links').stop().animate({'margin-top': newmar}, 200, function() { $('.drop_select a').css('background', 'none'); }); 
			$(document).unbind('click');	
		}
		return false;
		
	};
	
	// Trigger menu above on page load
	var GET = getQueryParams(document.location.search);
	if (GET['page'] == 'locations' && typeof(GET['brand']) == "undefined") {
		animationSpeed = 0;
		showLocationDrop();
		$(document).unbind('click');
		$('#location_links div a').bind('click', brandDropLink);
		var oldLocationButton = $('.drop_select a').html();
		$('.drop_select a').html('SELECT A BRAND BELOW TO VIEW THE AVAILABLE LOCATIONS');
	} else {
		$('.drop_select a').bind('click', showLocationDrop);	
	}
	
	function brandDropLink() {
		if (oldLocationButton != $('.drop_select a').html()) { 
			$('.drop_select a').animate({'opacity': 0}, 200, function() {
				$('.drop_select a').html(oldLocationButton).animate({'opacity': 1}, 200);												  
			});
			$('.drop_select a').bind('click', showLocationDrop);
			showLocationDrop();
		}
	};
	
	// Hover for Location Drop Menu Button
	$('.drop_select a').hover(function() {
		$(this).css('background', '#666666');		   
	}, function() {
		if (parseInt($('#location_links').css('margin-top'), 10) < ((marval-10)*-1)) {
			$(this).css('background', 'none');	
		}
	});
	
	// Location Menu Mouseovers
	$('#location_links div a').hover(function(){
		$(this).stop().animate({opacity: 0.6}, 100);  
	}, function() {
		$(this).stop().animate({opacity: 1}, 100); 
	});
	
	//$(document).bind('click', function() { $('#location_links').css('margin-top', '50px'); });
	
	// NEW Locatoin Brand Selector *still triggers the main selector!
	$('#location_links a').click(function() {
	
		var change = $(this).attr('rel');
		//alert(change);
		$('#brandselect').stop().val(change).trigger('change');
	});
	
	var selectRunning = false;
	
	// Team Brand Selector
	$('#brandselect').change(function(e) {
									  
		if (selectRunning === false) {
			selectRunning = true;	
		} else {
			return false;	
		}
									  
		var brand = $(this).val();
		if ($(this).attr('rel') == 'locations') {
			var solitaire = 'Solitaire '
		} else {
			var solitaire = '';	
		}
		var brandtxt = $("option:selected",this).text();
		var fullbrand = brandtxt;
		if (brandtxt == 'All Sales Locations' || brandtxt == 'All Service Locations') {
			var splittxt = brandtxt.split(' ');
			var newtxt=splittxt[1].replace("Solitaire ", "");
			var displaytxt = splittxt[0]+' '+solitaire+newtxt;
		} else {
			var newtxt=brandtxt.replace("Solitaire ", "");
			var displaytxt = solitaire+newtxt;	
		}
		brand = brand.toUpperCase();
		var count = 1;
		var display = '';
		var checking = '';
		
		
		
		if (brandlook[brand] != 'set') {
			
			
			for (var prop in jsteam[fullbrand.toUpperCase()]) {
				if (!jsteam[fullbrand.toUpperCase()].hasOwnProperty(prop) || prop == 'location') {
					//The current property is not a direct property of p
					continue;
				}
				//Do your logic with the property here
				display = "style='display: none;'";
				//$('#'+brand).append("<div id='' class='opt'>");
				$('#'+brand+' .this'+count).empty();
				
				var nm = 1;
				
				for (var person in jsteam[fullbrand.toUpperCase()][prop]) {
					if (!jsteam[fullbrand.toUpperCase()][prop].hasOwnProperty(person)) {
						//The current property is not a direct property of p
						continue;
					}
					
					var splitname = person.match(/([^ ]*)\ (.*)/);
					splitname.shift();
					
					if (prop != 'null') {
					
						var appendtxt = "";
						
						appendtxt += "<div class='team_container' id='team_container"+nm+"'>";
						appendtxt += "<div class='team' id='team"+nm+"'>";
						appendtxt += "<div class='hidden' style='display: block;'><a href='forms/form.php?to="+jsteam[fullbrand.toUpperCase()][prop][person]['Email']+"' class='iframe'></a></div>";
						appendtxt += "<img src='images/team/"+jsteam[fullbrand.toUpperCase()][prop][person]['Image']+"' border='0' class='pic' alt='"+person+"' />";
						appendtxt += "<div class='team_txt' id='team_txt"+nm+"'>";
						appendtxt += "<span class='name'><strong>"+splitname[0]+"</strong> "+splitname[1]+"</span><br />";
						appendtxt += jsteam[fullbrand.toUpperCase()][prop][person]['Title']+'<br/><br/>';
						appendtxt += "<div class='details' id='details"+nm+"'>";
						appendtxt += "<div style='float: right; margin-top: 12px; margin-right: 4px;'><img src='images/layout/email.gif' /></div>";
						
						if (jsteam[fullbrand.toUpperCase()][prop][person]['Mobile'] == "") appendtxt +='<br />';
						if (jsteam[fullbrand.toUpperCase()][prop][person]['Phone'] != "") appendtxt += 'Phone: '+jsteam[fullbrand.toUpperCase()][prop][person]['Phone']+'<br />';
						else appendtxt += '<br />';
						if (jsteam[fullbrand.toUpperCase()][prop][person]['Mobile'] != "") appendtxt += 'Mobile: '+jsteam[fullbrand.toUpperCase()][prop][person]['Mobile'];
						
						appendtxt += '</div>';
						appendtxt += '</div>';
						appendtxt += '</div>';
						appendtxt += '</div>';
					
					} else {
					
						var safeStreet = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Street']);
						var safeSuburb = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Suburb']);
						var safeState = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['State']);
						var safePostcode = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Postcode']);
						var phone = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Phone']);
						var fax = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Fax']);
									
						var safeName = encodeURIComponent(jsteam[fullbrand.toUpperCase()][prop][person]['Street']);
																										  
						var safeQuery = 'address='+safeStreet+',+'+safeSuburb+'+'+safeState+'+'+safePostcode+'&phone='+phone+'&fax='+fax+'&name='+safeName;
						
						var appendtxt = "";
						
						appendtxt += "<div class='loc_container' id='loc_container"+nm+"'>";
						appendtxt += "<div class='locations' id='locations"+nm+"'>";
						appendtxt += "<div class='hidden' style='display: block;'><a href='pages/locations/map.php?"+safeQuery+"'></a></div>";
						appendtxt += "<div class='imgdiv' style='background-image: url(images/locations/"+jsteam[fullbrand.toUpperCase()][prop][person]['img']+");'>";
						appendtxt += "<div class='viewmap'></div>";
						appendtxt += "</div>";
						appendtxt += "<div class='location_txt' id='location_txt"+nm+"'>";
						appendtxt += "<span class='name'><strong>"+splitname[0]+"</strong> "+splitname[1]+"</span><br />";
						appendtxt += jsteam[fullbrand.toUpperCase()][prop][person]['Street']+'<br/>';
						appendtxt += jsteam[fullbrand.toUpperCase()][prop][person]['Suburb']+', '+jsteam[fullbrand.toUpperCase()][prop][person]['State']+' '+jsteam[fullbrand.toUpperCase()][prop][person]['Postcode']+'<br/>';
						appendtxt += jsteam[fullbrand.toUpperCase()][prop][person]['Phone']+'<br/>';
						appendtxt += jsteam[fullbrand.toUpperCase()][prop][person]['Fax'];
						appendtxt += '</div>';
						appendtxt += '</div>';
						appendtxt += '</div>';
						
					
					}
					
					$('#'+brand+' .this'+count).append(appendtxt);
					
					nm++;
					
				}
				count++;
				brandlook[brand] = 'set';
			}
			
		}
		
		//$(".team .hidden a").fancybox();
		fancyfunction(".team .hidden a");
		fancyfunctionLocations(".locations .hidden a");
		
		var salestype = "";
		
		$('.teambrand[rel="current"]').fadeOut(400, function() {
			$('.opt').attr('id', '');
			$(this).attr('rel', '');
			var optid = 1;
			$('#'+brand+' .opt').each(function(index) {
				$(this).attr('id', 'opt'+optid);
				optid = optid+1;
			});
			
			if ($('#opt1').parent().children('#opt2').length) {
				salestype = $('#title_type').text();
			} else {
				lastclick = 'opt1';
				salestype = 'Sales';
			}
			
			if (lastclick == 'opt1') {
				$('#'+brand+' #opt2').css('z-index', '10');
				$('#'+brand+' #opt2 .team_container .team').fadeOut(0).css('display', 'none');
				$('#'+brand+' #opt2').css('visibility', 'none');
				$('#'+brand+' #opt1').css('visibility', 'visible');
				$('#'+brand+' #opt1').css('z-index', '999');
				$('#'+brand+' #opt1 .team').fadeIn(0);
				//var newclicktest = 'opt2';
			} else if (lastclick == 'opt2') {
				$('#'+brand+' #opt1').css('z-index', '10');
				$('#'+brand+' #opt1 .team_container .team').fadeOut(0).css('display', 'none');
				$('#'+brand+' #opt1').css('visibility', 'none');
				$('#'+brand+' #opt2').css('visibility', 'visible');
				$('#'+brand+' #opt2').css('z-index', '999');
				$('#'+brand+' #opt2 .team').fadeIn(0);
				//var newclicktest = 'opt1';
			}
			$('#'+brand).attr('rel', 'current');
			$('.hidden').stop().animate({opacity: 0}, 250);
			$('#'+brand).fadeIn(400, function() {
				selectRunning = false;
			});
		});
		
		$('#title').fadeOut(400, function() {
			displaytxt=displaytxt.replace(" Locations", "");
			$('#title_brand').replaceWith('<span id="title_brand"><strong>'+displaytxt+'</strong></span>');
			if ($('#team_contain').attr('class') != 'loc') {
				$('#title_type').replaceWith('<span id="title_type">'+salestype+'</span>');
			}
			$('#title').fadeIn(400);
		});
	});
	
	// Locations Hover
	$('#locations div a').animate({opacity: 0}, 0).css('background-color', '#000000');	
	
	$('#locations div a').hover(function() {
		$('#locations div a').not(this).stop().animate({opacity: 0.5}, 250);
		$(this).stop().animate({opacity: 0}, 250);
	});
	
	$('#locations').hover(function(){}, function() {
		$('#locations div a').stop().animate({opacity: 0}, 250);									
	});
	
	
	// General Pop-Up
	$('a.pop').fancybox({
		'autoDimensions'	:	false,
		'width'				:	720,
		'height'			:	420,
		'centerOnScroll'	:	'yes',
		'scrolling'			:	'no',
		'onStart'			:	function( links, index ){  
			
		},
		'onCleanup'			:	function( links, index ) {
			
		}
	});
	
	
	// Email Link Pop-Up
	fancyfunction(".team .hidden a");
	fancyfunctionLocations('.locations a, a.map');
	
	
});
	
	
function fancyfunction(idname) {
	
	$(idname).fancybox({
		'height'			:	280,
		'centerOnScroll'	:	'yes',
		'scrolling'			:	'no',
		'onStart'			:	function( links, index ){  
			
			var ext = '';
			var $thislink = $(links[index]);
			var url = $thislink.attr('href');
			var img = $thislink.parent().parent().children('img.pic').attr('src');
			if(img === undefined) { 
				img = '';
			} else {
				if (img.indexOf('.jpg') > -1) {
					ext = 'jpg';
				} else {
					ext = 'gif';
				}
				
				img = encodeURIComponent(img.substring(0, img.indexOf('.'+ext)));
				img = '&img=' + img;
				ext = '&ext=' + ext;
			}
			$thislink.attr('href', url+img+ext);
			$('.team .hidden').animate({opacity: 0}, 0).css('display', 'none');
		},
		'onCleanup'				:	function( links, index ) {
			var $thislink = $(links[index]);
			var url = $thislink.attr('href');
			url = url.split('&');
			url = url[0];
			$thislink.attr('href', url);
			$('.team .hidden').animate({opacity: 0}, 0).css('display', 'block');
		}
	});	
}

function fancyfunctionLocations(idname) {
	// Locations Pop-Up
	$(idname).fancybox({
		'height'			:	280,
		'centerOnScroll'	:	'yes',
		'scrolling'			:	'no',
		'onStart'			:	function( links, index ){  
			
		},
		'onCleanup'			:	function( links, index ) {
			
		}
	});
}

function validation(formname) {

	var error = "";
	var focusThis = "";
	
	$('form[name="'+formname.name+'"] .validate').css('border-color', '#666666').each(function() {
		if ($(this).is('select')) {
			/*if ($(this).attr('rel') != '') {
				var rel = $(this).attr('rel');
				if (rel.indexOf("NOT:") != -1) {
					var rel.split("NOT:");
				}
			}*/
			if ($(this).attr("selectedIndex") < 1) {
				error += "Select an option in the '"+$(this).attr('Name')+"' drop down.\n";
				$(this).css('border-color', '#CC0000');
			}
		} else {
			if ($(this).attr('name').toLowerCase() == 'email') {
				if (IsEmail($(this).val())) {
				} else {
					if ($(this).val() === '') {
						error += 'You must enter a valid email address\n';
						$(this).css('border-color', '#CC0000');
					} else {
						error += "The email address you entered is not valid\n";
						$(this).css('border-color', '#CC0000');
					}
				}
			} else if ($(this).attr('name').toLowerCase() == 'phone') {
				if ($(this).val().replace(/ /g,'').length	 < 8) {
					error += "The '"+$(this).attr('name')+"' field must contain at least 8 numbers.\n";	
					$(this).css('border-color', '#CC0000');
				}
			} else {
				if ($(this).val() === '') {
					error += "The '"+$(this).attr('name')+"' field cannot be left blank.\n";	
					$(this).css('border-color', '#CC0000');
				} /**/
			}
		}
	});

	/*

	if (document.mainform.email.value=="") {
		error += "Please enter your email address.\r\n";
		document.mainform.email.style.backgroundColor='#FFEFF0';
		//if (focusThis == "") { focusThis = document.mainform.Email; }
	}

	*/
	
	if (error != "") { alert("Please fix the following errors:\n\n"+error); return false; } 
	
}

function IsEmail(email) {
	var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return regex.test(email);
}

function clearField(a) {
	a.style.backgroundColor='#FFFFFF';
}

function closeBox() {
	window.top.window.$.fancybox.close(); 
} 

function getFile(fileName){
    oxmlhttp = null;
    try{
        oxmlhttp = new XMLHttpRequest();
        oxmlhttp.overrideMimeType("text/xml");
    }
    catch(e){
        try{
            oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
            return null;
        }
    }
    if(!oxmlhttp) return null;
    try{
       oxmlhttp.open("GET",fileName,false);
       oxmlhttp.send(null);
    }
    catch(e){
       return null;
    }
    return oxmlhttp.responseText;
}

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

(function($) {
	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
})(jQuery);

