// Image Preloading function

var myimages = new Array();
var serv = window.location.host;
var lImg, hashgo=true, lLink;
var imgs = preload('/static/img/contentbg-financial.jpg','/static/img/contentbg-health.jpg','/static/img/contentbg-office.jpg','/static/img/contentbg-resources.jpg');
var rstate = true;
var len = 1500;
var cheight, nheight;
var ready = function(be){
	// toggles our menu behaviour
	if(be == undefined){
		return rstate;
	}else if(be===true){
		$('#menu ul a').animate({opacity: 1}, 400, function(){
			rstate = true;
		});
	}else if(be===false){
		$('#menu ul a').animate({opacity: 0.5}, 200, function(){
			rstate = false;
		});
	}
}
String.prototype.rtrimslashes = function() {
	return this.replace(/\/$/g,'');
}
//sets some initial hash/path/last page variables.
var hash;
var section;
var path;
if(window.location.pathname==''){
	path = 'index';
}else{
	path = window.location.pathname;
}


//preloads images.
function preload(){
	for (x=0; x<preload.arguments.length; x++){
		myimages[x] = new Image();
		myimages[x].src = preload.arguments[x];
	}
	return myimages.slice();
}

// IE6 cmpat hashchange function to detect browser back/forward events to trigger ajax/click call

$(window).hashchange(function() {
	if(window.location.hash.replace('#','')==''){
		hash = 'index';
		section = 'index';
	}else{
		hash = window.location.hash.replace('#','');
		section = hash.split('/')[0];
	}
	var linx;
	if(hash=='index' && path != '/'){
		linx = $('a[href$="'+path+'"]');
	}else{
		linx = $('a[href$="/'+hash+'"]');
	}
		
	if(hashgo){
		$('a').removeClass('active');
		openUp(linx[0],null);
	}
});



// our click function, animates background images, disables menus&links, makes ajax request, and animates in new content.
function openUp(element, event){
	if(event!=null){
		event.preventDefault();
	}
	if(typeof(element)=='undefined'){
		element = $('a[href$="/'+hash+'"]')[0];
	}
	
	//console.log(lLink+' => '+element.href);
	var linky = element.href;
	//alert(/^http:\/\/.+\/index$/.test(linky));
	if(lLink == element.href || $('#content').is(':animated') || (typeof(lLink)=='undefined' &&  /^http:\/\/.+\/index$/.test(linky))) {
		//console.log('same page / anim not complete');
	}else{
		lLink = element.href;
		hashgo=false;
		var linkhref = element.href;
		var imgAnim;
		
		//sets active states on links clicked and related section links!
		$('#menu ul a').removeClass('active');
		if($(element).closest("div").hasClass('submenu')){
			$('.submenu ul a').removeClass('active');			
		}
		$(element).addClass('active');
		var aLink = $('a[href$="'+section+'"]')[0];
		if(typeof(aLink)!='undefined'){
			if($(element)[0].href.indexOf(aLink.href)>-1){
				$(aLink).addClass('active');
			}
		}
		
		if( linkhref.indexOf('about') > -1) {
			imgAnim = imgs[2];
		}else if( linkhref.indexOf('services') > -1) {
			imgAnim = imgs[2];
		}else if( linkhref.indexOf('vacancies') > -1) {
			imgAnim = imgs[3];
		}else if( linkhref.indexOf('resources') > -1) {
			imgAnim = imgs[3];
		}else if( linkhref.indexOf('general') > -1) {
			imgAnim = imgs[2];
		}else if( linkhref.indexOf('health') > -1) {
			imgAnim = imgs[1];
		}else if( linkhref.indexOf('financial') > -1) {
			imgAnim = imgs[0];
		}else if( linkhref.indexOf('sectors') > -1) {
			imgAnim = imgs[2];
		}else if( linkhref.indexOf('index') > -1) {
			imgAnim = imgs[3];
		}else if( linkhref.indexOf('contact') > -1) {
			imgAnim = imgs[3];
		}
		
		if(lImg != undefined){
			if(lImg.src==imgAnim.src){
				len = 0;
				//console.log('same image');
			}else{
				len = 1500
			}
		}
		lImg = imgAnim;
		
		$.ajax({
			// some default values we should always set
			url: linkhref,
			cache: true,
			// our ajax Events
			success: function(){},
			error: function(){},
			beforesend: function(){},
			complete: function(datar, textStatus){
				// get our data.
				var data = datar.responseText;
				var start = data.indexOf('<div id="content">')+18;
				var bstart = data.indexOf('<div id="container"');
				var end = data.indexOf('<div id="footer">');
				var content = data.substr(start,(end-start));
				var bcontent = '<div>'+data.substr(bstart,(end-bstart))+'</div>';
				var fcontent = data;
				$('#content').animate({opacity: 0}, 500, function(){
					//current content now GONE
					
					// Adds a wrapper to aid resize animation 
					if($('.faux-wrap').length<1){
						$('#container').wrap('<div class="faux-wrap" />');
					}
					$('.faux-wrap').css({'overflow':'hidden','height':nheight,'position':'relative'});
					$('#container').css('overflow','visible');
					$('#content').html('<div><div>'+content); // assign new content to container.
					
					// cleanup some onload js elements that might get missed
						
						if($('.fileinputs .file').length>0){
							$('.fileinputs .file').change(function(){
								// detects our change event
								var filename = $(this).val();
								var cutoff = filename.lastIndexOf('\\');
								filename = filename.substr(cutoff+1);
								$('.filename').text(filename);
								$('form input[name="filecheck"]').val('true');
							});
						}
						if($('#select-sectors').length>0){
							if($('#select-sectors').hasClass('small')){
								$('#select-sectors').selectmenu({
									width: 180,
									open: function(){$(this).selectmenu('disable',0)}
								});
							}else{								
								$('#select-sectors').selectmenu({
									width: 240,
									open: function(){$(this).selectmenu('disable',0)}
								});
							}
						}
						if($('#select-location').length>0){
							if($('#select-location').hasClass('small')){
								$('#select-location').selectmenu({
									width: 180,
									open: function(){$(this).selectmenu('disable',0)}
								});
							}else{
								$('#select-location').selectmenu({
									width: 240,
									open: function(){$(this).selectmenu('disable',0)}
								});
							}
						}
						//$('#select-orderby').yaselect();
						if($('#select-orderby').length>0){
							$('#select-orderby').selectmenu({
								width: 200,
								open: function(){$(this).selectmenu('disable',0)}
							});
						}
						$(".radio-styled").change(function(){
							if($(this).is(":checked")){
								$(".radio-styled:not(:checked)").next("label").removeClass("labelSelected");
								$(this).next("label").addClass("labelSelected");
							}
						});
						$('form.styled input[title]').parents('form').bind('submit',function(event){
							$(this).find('input[type="text"]').each(function(){
								if($(this).attr('title') == $(this).val()){
									$(this).val('');
								}
							});
						});
						$('form.styled input[title]').toggleVal({populateFrom: 'title'});
					
					// get new page title
					var matches = fcontent.match(/<title>(.*?)<\/title>/);
					var title = matches[1];
					document.title = title;
					
					// get new page classes for layout.
					var classes = $(bcontent).find('#container').attr('class');
					$('#container').removeClass();
					$('#container').addClass(classes);
					
					// set hash location for our history
					hash = window.location.hash = linkhref.replace(/^http:\/\/(.*?)\//, '');
					var valx;
					if (hash == 'index'){
						valx = {'opacity':'1', 'filter':''};
					}else{
						valx = {'opacity': '1'};
					}
					$('#content').animate(valx, 1500, function() {
						// new content now visible
						hashgo=true;
					});
					
				});
				
			}
		});
		
		if(ready()){
			// Animates the background image!!
			if($('.bgimg').last().css('backgroundImage') == 'none'){
				// sort out z-index order
				$('.bgimg').last().css('opacity','0');
				$('.bgimg').last().css('backgroundImage', 'url('+imgAnim.src+')');
				ready(false);
				$('.bgimg').last().animate({opacity: 1}, len, function() {
					// Animation complete. 
					ready(true);
				});				
			}else{
				$('.bgimg').first().css('backgroundImage', 'url('+imgAnim.src+')');
				ready(false);
				$('.bgimg').last().animate({opacity: 0}, len, function() {
					// Animation complete. 
					$('.bgimg').last().css('backgroundImage','none');
					ready(true);
				});						
			}
		}
	}
}
$(document).ready(function(){
   if($.browser.msie){
	   $('html').addClass('ie');
   }
   if($.browser.msie=="msie" && $.browser.version < 7){
   	// disable AJAX calls in IE6 //
   }else{
	 var adminarea = false;
	 var re = /\//g;
	for( var c = 0; re.exec(path); ++c );
	if(typeof(lLink)=='undefined' && (path =='index' || path == '/')){
		lLink = $('a[href$="/index"]')[0].href;
	}else if(c > 1){
		path = path.replace(/\//, '');
		paths = path.split('/');
		if(paths[0] == 'admin'){
			path = '/'+paths[1].rtrimslashes();
			adminarea = true;
		}else{
			path = '/'+paths.join('/').rtrimslashes();
			//console.log(path);			
		}
		var li = $('a[href$="'+path+'"]');
		if(li.length>0){
			lLink = $(li)[0].href;
		}
	}else{		
		lLink = $('a[href$="'+path+'"]')[0].href;
	}
	
	// reveals background image.
	$('.bgimg').css('display','block');
	// adds hash change event
  	$(window).hashchange();
	
	if(!adminarea){
		$('#menu ul a, .submenu a, #mast a.interactive').live('click', function(event){openUp(this, event)});
	}
	// Adds behaviour states to custom radio buttons
	$(".radio-styled").change(function(){
		if($(this).is(":checked")){
			$(".radio-styled:not(:checked)").next("label").removeClass("labelSelected");
			$(this).next("label").addClass("labelSelected");
		}
	});
	var i = new Image();
	i.src = "/static/img/radio-checked.png";
	if($('#select-sectors').length>0){
	if($('#select-sectors').hasClass('small')){
			$('#select-sectors').selectmenu({
				width: 180,
				open: function(){$(this).selectmenu('disable',0)}
			});
		}else{								
			$('#select-sectors').selectmenu({
				width: 240,
				open: function(){$(this).selectmenu('disable',0)}
			});
		}
	}
	if($('#select-location').length>0){
		if($('#select-location').hasClass('small')){
			$('#select-location').selectmenu({
				width: 180,
				open: function(){$(this).selectmenu('disable',0)}
			});
		}else{
			$('#select-location').selectmenu({
				width: 240,
				open: function(){$(this).selectmenu('disable',0)}
			});
		}
	}
	//$('#select-orderby').yaselect();
	if($('#select-orderby').length>0){
		$('#select-orderby').selectmenu({
			width: 200,
			open: function(){$(this).selectmenu('disable',0)}
		});
	}
	
	$('#select-orderby').bind('change',function(){
		if($(this).val() == "created"){
			$('#select-orderby-button').after($('<p class="date-choice"><input type="radio" name="date" value="today" id="today" /><label for="today">Posted today</label> <input type="radio" name="date" value="week" id="week" /> <label for="week">Last week</label> <br /><input type="radio" name="date" value="month" id="month" checked /> <label for="month">Last month</label></p>'));
		}
	});
	
	$("#container").bind('resize',function(e){
		// animate our container when #container element resizes		
		if(!$('#container').is(':animated')){
			nheight = $('#container').height();
			$('.faux-wrap').animate({'height': nheight}, 400, function(){
			   cheight = $('#container').height();
			   $('#container').height('auto');
			});
	    }
	});
	cheight = $('#container').height();
	
	// Adds validation to forms.
	$('form#vacancy_request, form#contact_request').live('mouseover', function(){
		$(this).validate({
			rules: {
				telephone:{
					minlength: 11,
					number: true
				},
				name:{
					required: true
				},
				company:{
					required: true
				},
				email:{
					required: true,
					email: true
				}
			},
			wrapper: 'div class="error" ',
			errorPlacement: function(error, element){
				error.insertAfter(element).css({'opacity':'0','display':'block'}).animate({'opacity':1},500);
				element.animate({'boxShadow':'0 0 7px #c00'}, 600);
			},
			hideError: function(error) {
				$(error).parent('div').fadeOut(1000);
				$(error).parent('div').prev('input').animate({'boxShadow':'0 0 5px #999999','color':'#333333'}, 300);
			},
			showError: function(error) {
				$(error).parent('div').css({'display':'block'}).animate({'opacity':1},500);
				$(error).parent('div').prev('input').animate({'boxShadow':'0 0 7px #c00'}, 600);
			}
		});
    });
	
	$('form#vacancy_apply').live('mouseover', function(){
		// adds validation to vacancy application
		$(this).validate({
			messages: {
				name: 'This field is required',
				email: 'Please enter a valid email address',
				phone: 'This field is required'
				},
			wrapper: 'div class="error" ',
			errorPlacement: function(error, element){
				error.insertAfter(element).css({'opacity':'0','display':'block'}).animate({'opacity':1},500);
				element.animate({'boxShadow':'0 0 7px #c00'}, 600);
			},
			hideError: function(error) {
				$(error).parent('div').fadeOut(1000);
				$(error).parent('div').prev('input').animate({'boxShadow':'0 0 5px #999999','color':'#333333'}, 300);
			},
			showError: function(error) {
				$(error).parent('div').css({'display':'block'}).animate({'opacity':1},500);
				$(error).parent('div').prev('input').animate({'boxShadow':'0 0 7px #c00'}, 600);
			}			
		});
    });
	$('.fileinputs input.file').bind(
		"mouseover mouseout",
		function( event ){
			if(event.type=="mouseover"){
				document.body.style.cursor = 'pointer';
			}else{
				document.body.style.cursor = 'default';
			}
		}
	);
	
	$('a.jback').live('click', function(event){
		event.preventDefault();
		history.go(-1);
	});
	
	// Adds css transition to form elements.
	if(!$('html').hasClass('ie')){
		$('form.styled input[type="text"], form.styled textarea').live('focus',function(event){
			// adds FX to TEXT INPUTS
			if(!$(this).hasClass('error')){
				$(this).animate({'backgroundColor':'#ffffff', 'boxShadow':'0 0 5px #333333'}, 300);
			}else{	
				$(this).animate({'backgroundColor':'#ffffff'}, 300);
			}
		});
		$('form.styled input[type="text"], form.styled textarea').live('blur',function(event){
			// adds FX to TEXT INPUTS
			if(!$(this).hasClass('error') && $(this).val().length < 1){
				$(this).animate({'backgroundColor':'#eeeeee','boxShadow':'0 0 5px #999999'}, 300);
			}else if($(this).val().length < 1){
				$(this).animate({'backgroundColor':'#eeeeee'}, 300);
			}
		});
	}
	
	if($('form.styled input[title]').length!=0){
		$('form.styled input[title]').toggleVal({populateFrom: 'title'});
	}
	
	$('form.styled input[title]').parents('form').bind('submit',function(event){
		$(this).find('input[type="text"]').each(function(){
			if($(this).attr('title') == $(this).val()){
				$(this).val('');
			}
		});
	});
	
	$('form.styled input[type="submit"]').live({
		mouseenter: function(){
			// adds FX to SUBMIT INPUTS HOVER
			$(this).animate({'boxShadow':'0 0 5px #555555','color':'#000000'}, 300);
		},
		mouseleave: function(){
			// adds FX to SUBMIT INPUTS OUT
			$(this).animate({'boxShadow':'0 0 5px #999999','color':'#333333'}, 300);
		}
    });
	
	//removes whitespace from number input
	$('input.number').live('change',function(){
		$(this).val($(this).val().replace(/ /gi, ""));
	});
			
	// Adds css transition to links.
	$('#content a, #menu a').live({
		mouseenter: function(){
			// adds FX to SUBMIT INPUTS HOVER
			$(this).animate({'color':'#000000'}, 300);
		},
		mouseleave: function(){
			// adds FX to SUBMIT INPUTS OUT
			$(this).animate({'color':'#383838'}, 300);
		}
    });
   }
   /*
   if($('#active-record')){
	   //alert(myjsobj);
   }*/
   
   // vacancy edit / display toggle.
   $('input.edit').click(function(){
		$('.admin div.edit').css('display','block');
		$('.admin div.display').css('display','none');
		$(this).attr('disabled',true);
		$('input.display').removeAttr('disabled');
	});
   $('input.display').click(function(){
		$('.admin div.display').css('display','block');
		$('.admin div.edit').css('display','none');
		$(this).attr('disabled',true);
		$('input.edit').removeAttr('disabled');
	});
   
   // datepicker!
   if($('.date-picker').length>0){
   	$('.date-picker').datepick();
   }
   
   if($('.admin-table .vacancy-check-all')){
	   $('.admin-table .vacancy-check-all').click(function(){
			$('.vacancy-check').each(function(){
				if($(this).attr('checked') == 'checked'){
					$(this).attr('checked',false);
				}else{
					$(this).attr('checked',true);
				}
			});
		});
   }
   
	if($('.fileinputs .file').length>0){
		$('.fileinputs .file').change(function(){
			// detects our change event
			var filename = $(this).val();
			var cutoff = filename.lastIndexOf('\\');
			filename = filename.substr(cutoff+1);
			$('.filename').text(filename);
			$('form input[name="filecheck"]').val('true');
		});
	}
});
