/**
 * @author Laurence Gush
 */
 
//$.address.value(location.href.substring(location.hostname.length + 14));

jQuery.noConflict();

(function($){

	initaddress= function(init){
	
		$.address.change(function(event){
			var aref = "http://" + location.hostname + event.value;
			if(init){
				init=false;
				if (location.hash=='#/index.html' || location.hash=='#/dev/' || !location.hash){
					$("#mid").show(0);
				}else{
					$('#mid').fadeTo(250,.5);
					$('#loading').show(0);
					clickit(aref);
				}
			}else{
				clickit(aref);	
			}
		})
	}
			
	clickit= function(aref){
		$.Tache.Get({
			url: aref+'?template=none',
			success: function(htmldata){
				$('#mid').hide(0,function(){
					$('#loading').hide(0);
					$('#mid').css({opacity:1}).html($(htmldata).find('#mid > *')).fadeIn(500);
					var newtitle = htmldata.match('<title>[\n\r\s]*(.*)[\n\r\s]*</title>'),
						newBodyClasses= htmldata.match('<body class="[\n\r\s]*(.*)[\n\r\s]*">'),
						curBodyClasses= $('body').attr('class');
						
					var nBcStart=newBodyClasses[1].indexOf('page'),
						nBcPosEnd=newBodyClasses[1].indexOf(' ',newBodyClasses[1].indexOf('page'));
					var nBcEnd=(nBcPosEnd>-1 ? nBcPosEnd : 1000);
					var newBodyClass=newBodyClasses[1].substr(nBcStart,nBcEnd);
					
					var cBcStart=curBodyClasses.indexOf('page'),
						cBcPosEnd=curBodyClasses.indexOf(' ',curBodyClasses.indexOf('page'));
					var	cBcEnd=(cBcPosEnd>-1 ? cBcPosEnd : 1000);
					var	curBodyClass=curBodyClasses.substr(cBcStart,cBcEnd);

					document.title = newtitle[1];
					$('body').removeClass(curBodyClass).addClass(newBodyClass);
				})
			},
			error: function(){
				$('#mid').html("<div id='main'><p>Sorry page not found</p></div>").fadeIn();
				document.title = "website - 404 error";
			}
		});
	}
	
	tache= function(aref){
		$.Tache.Get({
			url: aref+'?template=none',
			success: function(htmldata){
				htmdata=htmldata;
				linkObj[aref] = 'success';
			},
			complete: function(request, status){
				linkObj[aref] = status;
			}
		});
	}
	
	loading= function(aref,fade){
		if (linkObj[aref] == "loading") {
			if (fade) {
				$('#mid').fadeTo(100,.5);
				$('#loading').show(100);
			}
			t = setTimeout("loading('" + aref + "',false)", 100);
		}
		else if (linkObj[aref] == "error") {
			//TODO something 404
		}else {
			var arefcut=location.hostname.length+7;
			$.address.value(aref.substring(arefcut));
		}
	}
	
	wherearethey= function(obj){
		var i=0;
		while (i < linkArray.length) {
			var lref = linkArray[i].replace(/[^a-zA-Z0-9]/g,"");
			eval("rect" + lref + "=null");
			i++;
		}
		$(obj).each(function(){
			var aref=this.href.replace(/[^a-zA-Z0-9]/g,"");
			eval("rect"+aref+"= new rectObj();");
			eval("rect"+aref+"={"+
			"top:parseInt($(this).offset()['top']),"+
			"right:parseInt(($(this).offset()['left']+$(this).innerWidth())),"+
			"bottom:parseInt(($(this).offset()['top']+$(this).innerHeight())),"+
			"left:parseInt($(this).offset()['left']) }");
		});
		var $links = $("a").filter(function(){
			return this.hostname == location.hostname;
		});
		linkArray.length=0;
		$.each($links, function(){
			var aref =this.href.replace(/[\W]+$/,"");
			linkArray[linkArray.length] = aref;
		});
		linkArray = uniqueArr(linkArray);
	};
	
	moving= function(obj){
		$(obj).mousemove(function(e){
			var i=0;
			while (i < linkArray.length){
				var aref = linkArray[i];
				i++;
				if (!linkObj[aref]) {
					raref=aref.replace(/[^a-zA-Z0-9]/g,"");
					if (eval("rect" + raref)) {
						var pad = 50;
						if (eval("e.pageY >= rect" + raref + ".top - pad && e.pageY <= rect" + raref + ".bottom + pad && e.pageX >= rect" + raref + ".left - pad && e.pageX <= rect" + raref + ".right + pad")) {
							linkObj[aref] = "loading";
							tache(aref);
						}
					}
				}
			}
		})
	};
	
	adlive= function(not){
		$('a').live('mouseover',function(){
			var ajax=true, aref = this.href;
			if (aref.indexOf('#')>-1 || aref.indexOf('?')>-1 || aref.indexOf(not)>-1 || aref.indexOf('/edit')>-1 ) {ajax = false;};
			if (this.hostname == location.hostname && ajax) {
				if (!linkObj[aref]) {
					linkObj[aref] = "loading";
					tache(aref);
				}
			}
		});
		$('a').live('click', function(){
			var ajax=true, aref = this.href;
			if (aref.indexOf('#')>-1 || aref.indexOf('?')>-1 || aref.indexOf(not)>-1 || aref.indexOf('/edit')>-1 ) {ajax = false};
			if (this.hostname == location.hostname && ajax) {
				loading(aref,true);
				return false;
			}
		});
	}
		
	uniqueArr= function(a){
		var temp = new Array();
		for (i = 0; i < a.length; i++) {
			if (!contains(temp, a[i])) {
				temp.length += 1;
				temp[temp.length - 1] = a[i];
			}
		}
		return temp;
	};
	
	contains = function(a, e){
		for (j = 0; j < a.length; j++) 
			if (a[j] == e) 
				return true;
		return false;
	};
	
	linkObjs= function(){
		this.name="";
		this.rect=new rectObj;
	}
	
	rectObj = function(){
		this.top = 0;
		this.right = 0;
		this.bottom = 0;
		this.left = 0;
	}

	colours = function(ele){
		$(ele).append('<ul id="colours"><li><span class="white first"></span></li><li><span class="pink last"></span></li></ul>');
		$('#colours span').click(function(){
			var curBodyClasses= $('body').attr('class'),
				newBodyClass=$(this).attr('class').substring(0,( $(this).attr('class').indexOf(' ')>-1 ? $(this).attr('class').indexOf(' ') : 1000 ));
			var cBcStart=curBodyClasses.indexOf('col'),
				cBcPosEnd=curBodyClasses.indexOf(' ',curBodyClasses.indexOf('col'));
			var	cBcEnd=(cBcPosEnd>-1 ? cBcPosEnd : 1000);
			var	curBodyClass=curBodyClasses.substr(cBcStart,cBcEnd);
			
			$('body').removeClass(curBodyClass).addClass('col' + newBodyClass);
			setCookie('colour',newBodyClass,365);
		})
		$('#colours li').hover(function(){
			spheight=$(this).find('span').height();
			$(this).find('span').stop().animate({height:$(this).height()},250)
		},function(){
			$(this).find('span').stop().animate({height:spheight},250,function(){
				$(this).css({height:''})
			})
		})
	}
	
	slider = function(ele){
		$(ele).nivoSlider({
		effect:'sliceDown', //Specify sets like: 'fold,fade,sliceDown'
		slices:15,
		animSpeed:500,
		pauseTime:10000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:false, //Only show on hover
		controlNav:true, //1,2,3...
		controlNavThumbs:false, //Use thumbnails for Control Nav
      	controlNavThumbsFromRel:false, //Use image rel for thumbs
		controlNavThumbsSearch: '.jpg', //Replace this with...
		controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
		keyboardNav:false, //Use left & right arrows
		pauseOnHover:true, //Stop animation while hovering
		manualAdvance:false, //Force manual transitions
		captionOpacity:0.8, //Universal caption opacity
		beforeChange: function(){},
		afterChange: function(){},
		slideshowEnd: function(){} //Triggers after all slides have been shown
	})
	}

})(jQuery);

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString()) + 'path=/';
}

function getCookie(c_name){
if (document.cookie.length>0){
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1){
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function scale() {
	var myWidth = 0, myHeight = 0;
	myWidth = jQuery(window).width();
	if (myWidth > 1300) {
 		jQuery('body').css({'font-size':'100%'});
 		}
 	else if(myWidth > 800) {
 		jQuery('body').css({'fontSize' : ((myWidth * myWidth) * - 0.000093 ) + (myWidth * 0.2475) - (64.66) + "%"});
 		}
	else {
		jQuery('body').css({'fontSize':'74%'});
	};
};

jQuery(function(){
	//$('body').append('<div id="loading"><div class="inner"></div></div>');
	//initaddress(true);
	//$('#rapidcontactForm label,form.search label').inFieldLabels().addClass('posAbs');
	//$('#formDir label').inFieldLabels().addClass('posAbs').siblings('input').css({width: '10.5em'});
	//hitbox("#content");
	//linkObj = new Object();
	//linkArray = new Array();
	//wherearethey('a');
	//moving('body');
	//adlive('dashboard');
	//stream("body");
	window.onresize = scale;
	//colours('#header');
	//slider('#slider')

});


















