var preloadImgList = [];
var isPlaying = false;
var videoTimer;
var pointer = 0;
var imageList;
var vidLoaded = false;

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
	window.onload = func;
  } else {
	window.onload = function() {
	  if (oldonload) {
		oldonload();
	  }
	  func();
	}
  }
};

// BROWSER SPECIFIC FUNCS -----------------------------------
var isiPad = navigator.userAgent.match(/iPad/i) != null;

// EASING EQUATIONS -----------------------------------
function easeQuad(from, change, totalFrames, frame) {
	return (change*frame/totalFrames)*(frame/totalFrames)+from;
};


// HERO SLIDER PLUGIN -----------------------------------------------------------------------------------------------		
var HeroSlider = function(id) {

	this.id = $(id);
	this.timeOut = "";
	this.containerWidth  = this.id.offsetWidth;
	this.containerHeight = this.id.offsetHeight; 	
	this.init();
	this.initFlipNav();	
};

HeroSlider.prototype.init = function() {

	this.preCalcPos = [];	
	this.sliderItemsPointer = 0;
	this.nextItem = 0;
	this.sliderItems = getElementsByClass('heroItem');
	this.sliderItemsCount = this.sliderItems.length;
	this.sliderItemNumber = this.sliderItems.length;
	while (this.sliderItemsCount--) {
		this.preCalcPos.push( -(this.sliderItems[this.sliderItemsCount].offsetWidth + 20 ) * this.sliderItemsCount);
	};
	this.preCalcPos.reverse();
};

HeroSlider.prototype.initFlipNav = function() {
	me = this; //scoping issues, keep!
	this.flipNav = $('heroFlipper');
	this.flipNav_els = this.flipNav.getElementsByTagName('a');
	for (i=0; i < this.flipNav_els.length; i++) {			
		this.flipNav_els[i].onclick = function(i) { return function(e) { me.goTo(i); return false; }; }(i);	
		if (i==0) {
			addClass(this.flipNav_els[i], 'focus');
		};
	};
};

HeroSlider.prototype.updateFlipNav = function(s) {
	var p = this.flipNav_els.length;
	while (p--) {
		removeClass(this.flipNav_els[p], 'focus');
	};
	addClass(this.flipNav.getElementsByTagName('a')[s], 'focus');
};

HeroSlider.prototype.goTo = function(i) {
	clearTimeout(this.timeOut);
	s = i;		
	if (typeof i == 'string') {	//scroll to named item
		for (i=0; i < this.sliderItems.length; i++) {
			if (this.sliderItems[i].id == s) {
				me.goTo(i); // call again with correct number in param instead of ID name
			};
		};
	}
	else { //scroll to item by number
		animate('hero_rails', 'left', {'to':this.preCalcPos[s]});
		this.updateFlipNav(s);
	};
	this.sliderItemsPointer = i;
	if(this.sliderItemsPointer == (this.sliderItemNumber - 1))
	{
		this.nextItem = 0;
	}
	else
	{
		this.nextItem = this.sliderItemsPointer + 1;
	}
	if(isiPad || !navigator.userAgent.match(/Mobile/i))
	{
		this.timeOut = setTimeout(function(){promo_slider.goTo(promo_slider.nextItem)}, 5000);
	}
};	
//-----------------------------------------------------------------------------------------------	
		
HeroSlider.prototype.autoPlay = function()
{
	this.timeOut = setTimeout(function(){promo_slider.goTo(promo_slider.nextItem)}, 5000);
}
	
// UNIVERSAL ONLOAD -----------------------------------------------------------------------------------------------	
function getElementsByClass(searchClass, node, tag) { // oldskool
	var classElements = [];
	var node = node || document;
	var tag = tag || '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
};
//-----------------------------------------------------------------------------------------------	
	
function hasClass(el, cls) {
	return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
};

function addClass(el, cls) {
	if (!this.hasClass(el, cls)) el.className += " "+cls;
};

function removeClass(el, cls) {
	if (hasClass(el, cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		el.className=el.className.replace(reg,' ');
	}
};


// -----------------------------------------------------------------------------------------------		
addLoadEvent(function() {
	if ($('hero')) {
		promo_slider = new HeroSlider('hero');
		if(isiPad || !navigator.userAgent.match(/Mobile/i))
		{
			promo_slider.autoPlay();
		}
	};
});
function addJavascript(jsname) {
var th = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
	
// ANIMATE FUNCTION -----------------------------------------------------------------------------------------------	
// rehashed from original site design version
function animate(el, attr, opts) {
						// opts = {to, time, fps, onComplete}
	this.el = $(el);
	this.attr = attr;
	this.to	  = parseInt(opts.to);
	this.time = opts.time || 800; // time in ms
	this.fps  = opts.fps || 20; // fps
	this.from = parseInt(this.el.style.left) || 0; //either its set inline or its 0
	this.onComplete = new Function(opts.onComplete);
	
	//if (isiPad) {
	if (false) {
//		addClass instead - translate3d
	}
	else {
		var change       = this.to - this.from;
		var interval     = Math.ceil(700 / this.fps);
		var totalFrames  = Math.ceil(this.time / interval);
		var fixedStep    = change / totalFrames;
		for (i = 1; i <= totalFrames; i++) {
			(function() {
				var frame = i;
				function innerChangeWidth() {
					var increase = easeQuad(this.from, change, totalFrames, frame);
					this.el.style[this.attr] = increase + "px";
					if (frame == totalFrames) { 
						this.el.style.filter = '';
						this.inProgress = false;
						timer = '';
						endAnimation();
					};
				};
				timer = setTimeout(innerChangeWidth, interval * frame);
			})();
		};
	};
	
	function endAnimation() {
		//do clean up 			
		this.onComplete();
	};
};
// ANIMATE FUNCTION -----------------------------------------------------------------------------------------------	



isOpen = false;
threadID = "";
canGetThread = false;
threadTimer = "";
function $(el) { return document.getElementById(el); };


function newChat(theName)
{
	if($('chatMessageBox').value != "")
	{
		$('chatMessageBox').value = "";
		$('chatMessageBox').focus();
		$('chatSend').onclick = function() {alert('Can not send message. Please try again.');};
		$('chatMessageBox').onkeypress = function(event) {if (event.keyCode==13)alert('Can not send message. Please try again.');};
		var newChatSend = new ajaxRequest('../serverClasses/im.api.php', 'un=www&pw=Diamonds1&f=newIM&t=###&m=My name is ' + theName, hasNewChat);
		newChatSend.sendPostData();
	}
}
function hasNewChat(chatID)
{
	threadID = chatID.responseText;
	$('chatSend').onclick = function() {sendMessage($('chatMessageBox').value);};
	$('chatMessageBox').onkeypress = function(event) {if (event.keyCode==13)sendMessage($('chatMessageBox').value);};
	canGetThread = true;
	var sendMes = new ajaxRequest('../serverClasses/im.api.php', 'un=wwws&pw=Diamonds1&f=sendIM&t=' + threadID + '&m=Thank you. A diamond expert will be with you shortly.', messageSent);
	sendMes.sendPostData();
}


function sendMessage(msg)
{
	if(threadID != "" && $('chatMessageBox').value != "")
	{
		$('chatMessageBox').value = "";
		$('chatMessageBox').focus();
		var sendMessage = new ajaxRequest('../serverClasses/im.api.php', 'un=www&pw=Diamonds1&f=sendIM&t=' + threadID + '&m=' + msg, messageSent);
		sendMessage.sendPostData();
	}
}
function messageSent(returned)
{
	//get messages??
	if(returned.responseText != "")
	{
		alert("Send Error!");
	}
	else
	{
		$('chatMessageArea').scrollTop = $('chatMessageArea').scrollHeight;
		getThread();
	}
}

function getThread()
{
	if(canGetThread)
	{
		clearTimeout (threadTimer);
		canGetThread = false;
		var sendMessage = new ajaxRequest('../serverClasses/im.api.php', 'un=www&pw=Diamonds1&f=getThread&t=' + threadID + '&m=0', gotThread);
		sendMessage.sendPostData();
	}
}

function gotThread(chatText)
{
//		chatText.responseText
	if($('chatMessageArea').innerHTML != chatText.responseText)
	{
		$('chatMessageArea').innerHTML = chatText.responseText;
		$('chatMessageArea').scrollTop = $('chatMessageArea').scrollHeight;
	}
	canGetThread = true;
	threadTimer = setTimeout('getThread()', 2000);
}

function startChat() 
{
	if (isOpen) { 
		$('chatNotify').style.bottom = "-278px";
		clearTimeout (threadTimer);
		threadID = "";
		isOpen = false;
	}
	else {
		isOpen = true;
		threadID = "";
		clearTimeout (threadTimer);
		$('chatNotify').style.bottom = "-1px";
		$('chatMessageArea').innerHTML = "<p style=\"font-weight:normal; border-bottom: 1px dotted #F1F1F1;\"><span style=\"font-weight:bold;\">Please enter your name...</span></p>";
		$('chatMessageBox').focus();
		$('chatSend').onclick = function() {newChat($('chatMessageBox').value);};
		$('chatMessageBox').onkeypress = function(event) {if (event.keyCode==13)newChat($('chatMessageBox').value);};
	}
}

// AJAX FUNC
function ajaxRequest(theURL, sendString, callbackFunction) {
	var thisRequestObject;
	thisRequestObject = initiateRequest();
	thisRequestObject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	thisRequestObject.onreadystatechange = processRequest;
	function initiateRequest()
	{
		if (window.XMLHttpRequest)
		{
			return new XMLHttpRequest();
		}
		elseif (window.ActiveXObject)
		{
		 return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	function processRequest() {
	    if(thisRequestObject.readyState == 4 && thisRequestObject.status == 200) {
			if (callbackFunction) {
				callbackFunction(thisRequestObject, sendString);
			}
			else {
				//alert("There was an error: (" + thisRequestObject.status + ") " + thisRequestObject.statusText);
			}
		}
	}

	function processRequest()
	{
		if (thisRequestObject.readyState == 4)
		{
			if (thisRequestObject.status == 200)
			{
				if (callbackFunction)
				{
					callbackFunction(thisRequestObject, sendString);
				}
			}
			else
			{
				//alert("There was an error: (" + thisRequestObject.status + ") " + thisRequestObject.statusText);
			}
		}
	}

	this.sendGetData = function() 
	{
		if (theURL)
		{
			thisRequestObject.open("GET", theURL, true);
			thisRequestObject.send(sendString);
		}
	}

	this.sendPostData = function()
	{
		if (theURL)
		{
			thisRequestObject.open("POST", theURL, true);
			thisRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			thisRequestObject.send(sendString);
		}
	}
}


// TWITTER
function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
	var username = twitters[i].user.screen_name;
	var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
	  return '<a href="'+url+'">'+url+'</a>';
	}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
	  return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
	});
	statusHTML.push('<p><span class="tG"><a target="_blank" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id_str + '">'+status+'</a></span> <a style="font-size:85%" target="_blank" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id_str + '">' + relative_time(twitters[i].created_at) + '</a></p>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
};

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
	return 'less than a minute ago';
  } else if(delta < 120) {
	return 'about a minute ago';
  } else if(delta < (60*60)) {
	return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
	return 'about an hour ago';
  } else if(delta < (24*60*60)) {
	return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
	return '1 day ago';
  } else {
	return (parseInt(delta / 86400)).toString() + ' days ago';
  }
};




// IMAGE QUEUING -----------------------------------------------------------------------------------------------		
var imagesQ = {
	onComplete: function(){},
	onLoaded: function(){},
	current: null,
	qLength : 0,
	images: [],
	inProcess : false,
	queue:[],
	queue_images: function(){
		var arg=arguments;
		for (var i=0;i<arg.length;i++){
			if (arg[i].constructor === Array){
				this.queue= this.queue.concat(arg[i]); 
			}else if (typeof arg[i]==='string') {		
				this.queue.push(arg[i]);
			}
		}				
	},
	process_queue: function() {
		this.inProcess = true;
		this.qLength += this.queue.length;
		while(this.queue.length >0) {
			this.load_image(this.queue.shift());
		}
		this.inProcess = false;
	},
	load_image: function(imageSrc) {
		var th = this;
		var im = new Image;
		im.onload = function(){
			th.current = im;
			th.images.push(im);
			(th.onLoaded)();
			if(th.queue.length > 0 && !th.inProcess) {
				th.process_queue();
			}
			if(th.qLength == th.images.length){ 
				(th.onComplete)(); 
			}
		}
		im.src = imageSrc; 
	}
};


// PLAY VIDEO ---------------------------------------------------------------------

var playVideo = {
	isPlaying : null,
	el : $('play'),
	videoTimer : null,
	pointer : 0,
	
	play : function() {
		if(vidLoaded)
		{
			this.videoTimer = window.setInterval(this.changeImg, 40);
			this.isPlaying = true;	
			$('videoLoading').style.clip = "rect(45px, 45px, 90px, 0px)";
			$('videoLoading').style.top = "125px";
		}
	},
	
	stop : function() {
		clearInterval(this.videoTimer);
		this.videoTimer = null;
		this.isPlaying = false;
		$('videoLoading').style.clip = "rect(0px, 45px, 45px, 0px)";
		$('videoLoading').style.top = "170px";		
	},
	
	playPause : function() {
		if (this.isPlaying == true) {
			this.stop();
		}
		else {	
			this.play();
		};
	},
	
	changeImg : function() {
		this.pointer = (this.pointer >= imageList.length-1) ? 0 : this.pointer+1;
		if(this.pointer>0)
		{
			imageList[this.pointer-1].style.display = 'none';
		}
		else
		{
			imageList[imageList.length-1].style.display = 'none';
		}
		imageList[this.pointer].style.display   = 'block';
		
	}
	
};


// MESSAGEBOX ------------------------------------------------------------------------------------------------			
var messageBox = function(img) {

	if (!$('modalInner')) {
		var modalBg = document.createElement('div');
			modalBg.id = "modalBg";
			modalBg.style.width = "100%"; // document.documentElement.offsetWidth +"px" || document.body.clientHeight || "100%";
			modalBg.style.height = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) + "px";
			modalBg.style.display = "block";
			modalBg.style.position = "absolute";
			modalBg.style.top = modalBg.style.left = "0";
			modalBg.style.zIndex = "1000";
			modalBg.style.backgroundColor = "rgba(0, 0, 0, 0.1)";
			modalBg.style.cursor = "pointer";
			modalBg.onclick = function() { this.style.display = 'none'; document.onkeypress = null; };

		var modalInner = document.createElement('div');
			modalInner.id = "modalInner";
			modalInner.style.cursor = "default";
			modalInner.style.display = "block";
			modalInner.style.position = "relative";
			modalInner.style.padding = "20px";
			modalInner.style.paddingBottom = "15px";
			modalInner.style.margin = "5% auto";
			modalInner.style.backgroundColor = "#fff";
			modalInner.style.borderRadius = modalInner.style.MozBorderRadius = modalInner.style.WebkitBorderRadius = "6px";
			modalInner.style.BoxShadow 	  = modalInner.style.MozBoxShadow    = modalInner.style.WebkitBoxShadow    = "0 10px 25px rgba(0, 0, 0, 0.5)";
			modalInner.style.border = "1px solid #fff";
			modalInner.style.zIndex = "51";
			modalInner.style.maxWidth = "480px";
			modalInner.style.minWidth = "300px";
			modalInner.style.width = "60%";
			
		var modalClose = document.createElement('img');
			modalClose.id = "modalClose";
			modalClose.src = "img/cross.png";
			modalClose.style.cursor = "pointer";
			modalClose.style.position = "absolute";
			modalClose.style.top = modalClose.style.right = "3px";
			modalClose.onclick = function() { $('modalBg').style.display = 'none'; document.onkeypress = null; };

		var modalRing = document.createElement('img');
			modalRing.id = "modalRing";
			//modalRing.src = "images/loading.gif";
			//modalRing.style.width = "100%";

		modalInner.appendChild(modalClose);		
		modalInner.appendChild(modalRing);				
		modalBg.appendChild(modalInner);	
		document.body.appendChild(modalBg);
	};
	
	$('modalRing').src = img;
	$('modalRing').style.marginLeft = $('modalRing').style.marginTop = "0";
	$('modalBg').style.display = "block";
	
	document.onkeypress = function(e)
	{
		if ((e || event).keyCode == 27)
		{
			$('modalBg').style.display = 'none';
			return false;
		};
	};
};

//Basket functions
function fillAdd()
{
	if(window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST","includes/getAdd.php",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("num=" + document.getElementById("house").value + "&pc=" + document.getElementById("postcode").value);
	xmlhttp.onreadystatechange=function()
	{
		if(xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			add = xmlhttp.responseText;
			adds = add.split("#");
			document.getElementById("add1").value=adds[0];
			document.getElementById("add2").value=adds[1];
			document.getElementById("town").value=adds[2];
		}
	}
}

function pressEmail(name, company, email, msg, tel)
{
	//alert(name + company + email + msg);
	$('media').innerHTML = "Sending..."
	if(window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST","press-contact.php",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("name=" + name + "&company=" + escape(company) + "&email=" + escape(email) + "&message=" + escape(msg) + "&tel=" + escape(tel));
	xmlhttp.onreadystatechange=function()
	{
		if(xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			if(xmlhttp.responseText != "Done")
			{
				$('media').innerHTML = "<br/>Error: " + xmlhttp.responseText + "<br/>Please click <a href='?name=" + escape(name) + "&company=" + escape(company) + "&email=" + escape(email) + "&message=" + escape(msg) + "&tel=" + escape(tel) + "'>here</a> to try again.<br/><br/>";
			}
			else
			{
				$('media').innerHTML = "<br/>Thanks, your message has been sent.<br/><br/><a href='?name=" + escape(name) + "&company=" + escape(company) + "&email=" + escape(email) + "&tel=" + escape(tel) + "'>&lt; Send another message</a><br/><br/>";
			}
		}
		else
		{
			$('media').innerHTML = "<br/>Error:  problem sending email.<br/>Please click <a href='?name=" + escape(name) + "&company=" + escape(company) + "&email=" + escape(email) + "&tel=" + escape(tel) + "&message=" + escape(msg) + "'>here</a> to try again.<br/><br/>";
		}
	}
}

function customerEmail(name, company, email, msg, tel)
{
	//alert(name + company + email + msg);
	$('media').innerHTML = "Sending..."
	if(window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST","customer-enquiry.php",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("name=" + name + "&company=" + escape(company) + "&email=" + escape(email) + "&message=" + escape(msg) + "&tel=" + tel);
	xmlhttp.onreadystatechange=function()
	{
		if(xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			if(xmlhttp.responseText != "Done")
			{
				$('media').innerHTML = "<br/>Error: " + xmlhttp.responseText + "<br/>Please click <a href='?name=" + escape(name) + "&company=" + escape(company) + "&email=" + escape(email) + "&tel=" + tel + "&message=" + escape(msg) + "'>here</a> to try again.<br/><br/>";
			}
			else
			{
				$('media').innerHTML = "<br/>Thanks, your message has been sent.<br/><br/><a href='?name=" + escape(name) + "&company=" + escape(company) + "&tel=" + escape(tel) + "&email=" + escape(email) + "'>&lt; Send another message</a><br/><br/>";
			}
		}
		else
		{
			$('media').innerHTML = "<br/>Error:  problem sending email.<br/>Please click <a href='?name=" + escape(name) + "&company=" + escape(company) + "&email=" + escape(email) + "&tel=" + escape(tel) + "&message=" + escape(msg) + "'>here</a> to try again.<br/><br/>";
		}
	}
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

function getScrollXY() {
				  var scrOfX = 0, scrOfY = 0;
				  if( typeof( window.pageYOffset ) == 'number' ) {
					 //Netscape compliant
					 scrOfY = window.pageYOffset;
					 scrOfX = window.pageXOffset;
				  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
					 //DOM compliant
					 scrOfY = document.body.scrollTop;
					 scrOfX = document.body.scrollLeft;
				  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
					 //IE6 standards compliant mode
					 scrOfY = document.documentElement.scrollTop;
					 scrOfX = document.documentElement.scrollLeft;
				  }
				  return [ scrOfX, scrOfY ];
				}

