// JavaScript Document

function init(){
	document.getElementById('searchInput').value = 'Title, Author or ISBN';	
}

function focusBtn(obj){
	obj.style.background = '#a8be14';
}

function blurBtn(obj){
	obj.style.background = '#869810';
}

function focusCartBtn(obj){
	document.getElementById(obj).setAttribute('class','cartBtnOver');
}
function blurCartBtn(obj){
	document.getElementById(obj).setAttribute('class','cartBtnIni');
}

function focusTxt(obj){
	if(obj.value == 'Title, Author or ISBN' || obj.value == 'Please enter' || obj.value == 'Incorrect code'){
		document.getElementById(obj.id).setAttribute('value', '');
		obj.value = '';
	}
	document.getElementById(obj.id).style.border = '1px solid #869810';
	document.getElementById(obj.id).style.color = '#666';
	document.getElementById(obj.id).style.font = 'normal normal medium/1em "Trebuchet MS", Arial, Helvetica, sans-serif';
	fail = "pass";
}
function blurTxt(obj){
	obj.style.border = '1px solid #c3d5e1';
	if(obj.value == '' && obj.id == 'searchInput'){
		obj.value = 'Title, Author or ISBN';
		obj.style.color = '#CCC';
		obj.style.font = 'italic normal medium/1em "Trebuchet MS", Arial, Helvetica, sans-serif';
	} else {
		obj.style.color = '#333';
		obj.style.font = 'normal normal medium/1em "Trebuchet MS", Arial, Helvetica, sans-serif';
	}
}

function addToCart(id){
	
	var qty = document.getElementById('qty').value;
	
	var params = 'product_id='+id+'&qty='+qty;
	
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				document.getElementById('cartBtn'+id+'').value = 'Added';
				getCart();
				var q = document.getElementById('qty').value;
				document.getElementById('addedTxt').innerHTML = '<span>'+q+'</span> items added to cart';
				fadeIn('addFader', 400);
				var f = setTimeout('fadeOut("addFader", 400)', 3000);
				var r = setTimeout('resetBtn(\'cartBtn'+id+'\')', 1000);
			} else {
				// this should never fire
				alert('Error adding item to cart!');	
			}
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/addToCart.php?"+params,true);
	xmlhttp.send();
	// return false cancels the a href link to the details page
	return false;
	
}

function addBundleToCart(id){
	var qty = document.getElementById('qty').value;
	
	var params = 'bundle_id='+id+'&qty='+qty;
	
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				document.getElementById('bundle'+id+'').value = 'Added';
				getCart();
				var q = document.getElementById('qty').value;
				document.getElementById('addedTxt').innerHTML = '<span>'+q+'</span> items added to cart';
				fadeIn('addFader', 400);
				var f = setTimeout('fadeOut("addFader", 400)', 3000);
				var r = setTimeout('resetBtn(\'bundle'+id+'\')', 1000);
			} else {
				// this should never fire
				alert('Error adding item to cart!');	
			}
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/addBundleToCart.php?"+params,true);
	xmlhttp.send();
}

// resets the cart button vale to 'add to cart'
function resetBtn(id){
	document.getElementById(id).value = '+ Add to cart';
	getCart();
}

function updateCart(item_id, qty){
	var q = document.getElementById(qty);
	//alert('item id = '+item_id+' qty = '+q);
	var params = 'item_id='+item_id+'&qty='+q.value;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				var y = setTimeout('getCart()', 900);
				var z = setTimeout('getTotalPrice(), 1300');
				var div_id = 'subtotal_'+item_id;
				var div = document.getElementById(div_id);
				div.innerHTML = '£'+xmlhttp.responseText;
				if(xmlhttp.responseText > 19.99){
					document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" id="checkoutBtn" name="checkoutBtn" class="btnIni" onclick="isShippingValid()" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
					document.getElementById('minOrder').innerHTML = '';
				}else{
					document.getElementById('minOrder').innerHTML = '<span>*</span> minimum order £100.00';
					document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" style="cursor:default" disabled="disabled" id="checkoutBtn" name="checkoutBtn" class="btnIni" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
				}
			} 
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/updateCart.php?"+params,true);
	xmlhttp.send();
}
function updateCart_bundle(item_id, qty){
	var q = document.getElementById(qty);
	//alert('item id = '+item_id+' qty = '+q);
	var params = 'item_id='+item_id+'&qty='+q.value;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				var y = setTimeout('getCart()', 900);
				var z = setTimeout('getTotalPrice(), 1300');
				var div_id = 'bundle_subtotal_'+item_id;
				var div = document.getElementById(div_id);
				div.innerHTML = '£'+xmlhttp.responseText;
				if(xmlhttp.responseText > 19.99){
					document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" id="checkoutBtn" name="checkoutBtn" class="btnIni" onclick="isShippingValid()" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
					document.getElementById('minOrder').innerHTML = '';
				}else{
					document.getElementById('minOrder').innerHTML = '<span>*</span> minimum order £100.00';
					document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" style="cursor:default" disabled="disabled" id="checkoutBtn" name="checkoutBtn" class="btnIni" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
				}
			} 
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/updateCart_bundle.php?"+params,true);
	xmlhttp.send();
}

function getDiscount(){
	var code = document.getElementById('discount').value;
	if(code == ""){
		alert('Please enter a discount code');
	}else{
		var params = 'code='+code;
		if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
			xmlhttp.onreadystatechange=function(){
			if (xmlhttp.readyState==4 && xmlhttp.status==200){
				if(xmlhttp.responseText != 'FAIL'){
					//var y = setTimeout('getCart()', 900);
					//var z = setTimeout('getTotalPrice(), 1300');
					document.getElementById('totalPrice').innerHTML = '<span>Total:</span> £'+xmlhttp.responseText;
					//document.getElementById('discount').value = "Applied";
					//document.getElementById('discount').disabled = "disabled";
					if(xmlhttp.responseText > 19.99){
						document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" id="checkoutBtn" name="checkoutBtn" class="btnIni" onclick="isShippingValid()" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
						document.getElementById('minOrder').innerHTML = '';
					}else{
						document.getElementById('minOrder').innerHTML = '<span>*</span> minimum order £100.00';
						document.getElementById('checkoutBtnDiv').innerHTML = '<input type="button" style="cursor:default" disabled="disabled" id="checkoutBtn" name="checkoutBtn" class="btnIni" onmouseover="focusBtn(this)" onmouseout="blurBtn(this)" value="Pay Now"  />';
					}
				} else {
					document.getElementById('discount').value = "Incorrect code";
				}
			}
		}
		xmlhttp.open("GET","../includes/ajax/getDiscount.php?"+params,true);
		xmlhttp.send();
	}
}

function getCart(){
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				if(document.getElementById('cartTop')){
					document.getElementById('cartTop').innerHTML = xmlhttp.responseText + ' items in cart';
				}
				// check tp see if we are on the viewCart page, if so, this will run
				var countElement = document.getElementById("cartCount");
				// now we check to see if that is null, if it's not, we have that element on our page so we can chenge the html
				if(countElement != null){
					countElement.innerHTML = 'You have <span>' + xmlhttp.responseText + '</span> items in your basket.';
					var c = document.getElementById('cartTop');
					if(c != null){
						c.innerHTML = xmlhttp.responseText + ' items in cart';
					}
				}
			} else {
				// this should never fire
				//alert('Error!');	
			}
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/getCart.php",true);
	xmlhttp.send();
}

function removeFromCart(id){
	var params = 'id='+id;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				var div_id = 'cartID'+id;
				var r = setTimeout('removeDiv("'+div_id+'","cartHolder"'+')', 600);
				var s = setTimeout('getCart()', 900);
				var p = setTimeout('getTotalPrice()', 1300);
			} else {
				// this should never fire
				alert('Error removing!');	
			}
	  
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/deleteFromCart.php?"+params,true);
	xmlhttp.send();
}
function removeDiv(divID, parentID){
	var t = setTimeout('doRemove(\''+divID+'\',\''+parentID+'\')' , 1500);
	fadeOut(divID, 500);
}
function doRemove(divID, parentID){
	//document.getElementById(parentID).removeChild(divID);
	//parentID.removeChild(parentID.divID);
}

function getTotalPrice(){
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	
		xmlhttp.onreadystatechange=function(){
	  
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
			if(xmlhttp.responseText != 'FAIL'){
				//document.getElementById('totalPrice').innerHTML = '<span>Total:</span> £0.00';
				document.getElementById('totalPrice').innerHTML = '<span>Total:</span> ' + xmlhttp.responseText;
				if(xmlhttp.responseText == "£0.00"){
					document.getElementById('checkoutBtn').setAttribute('disabled','disabled');
					document.getElementById('checkoutBtn').setAttribute('class','disabledBtn');
				}
			}
	    }
	  
	}
	xmlhttp.open("GET","../includes/ajax/getTotal.php",true);
	xmlhttp.send();
}



function isSearchValid(){
	
	var txt = document.getElementById('searchInput');
	
	if(txt.value == '' || txt.value == 'Please enter' || txt.value == 'Title, Author or ISBN'){
		txt.value = 'Please enter';
		txt.style.border = '1px solid #C00';
		txt.style.color = '#C00';
		txt.style.font = 'normal normal medium/1em "Trebuchet MS", Arial, Helvetica, sans-serif';
		return false;
	}else{
		document.getElementById('searchID').value = 421;
	}
	
}

function isShippingValid(){
	
	fail = '';
	
	for(i=0; i<document.shippingDetails.elements.length; i++){
		
		if(elemGetAttribute(document.shippingDetails.elements[i],"title") == "required" && document.shippingDetails.elements[i].value == "" || document.shippingDetails.elements[i].value == "Please enter"){
			document.getElementById(document.shippingDetails.elements[i].id).value = "Please enter";
			document.getElementById(document.shippingDetails.elements[i].id).style.border = "1px solid red";
			document.getElementById(document.shippingDetails.elements[i].id).style.color = "red";
			fail = "failed";
		}
		//document.write("The field name is: " + document.shippingDetails.elements[i].name + " and it's value is: " + document.shippingDetails.elements[i].value + ".<br />");
	}
	if(fail != "failed"){
		document.getElementById('shippingID').value = 421;
		open_modal('#alertDiv');
		//document.getElementById('shippingDetails').submit();
		//location.href='super_secret_submit_form.php';
	}
}

function submitForm(){
	
	if(document.getElementById('answer').value == 'Answer'){
		alert('Please answer the question before proceeding.\n\nYou can skip this step if you wish by clicking the \'Skip this step\' link');
		return false;
	}
	document.getElementById('shippingDetails').submit();
	
}

function skip_and_submitForm(){
	document.getElementById('shippingDetails').submit();
}

function elemGetAttribute(elem,attr) {
   try {
      return eval("elem."+attr);
   } catch (e) {
      return null;
   }
}

function open_modal(divID){
	//LOADING POPUP
	centerPopup(divID);
	//load popup
	loadPopup(divID),
					
	//CLOSING POPUP
	//Click the x event!
	$(divID+'Close').click(function(){
		disablePopup(divID);
	});
	
}


//////////////////////////////////////////////////  Fade Up Functions  ////////////////////////////////////////////////////////////////////
function fadeOut(thisId, speed) {
    var thisE = document.getElementById(thisId);
    thisE.style.zoom = 1; //needed for IE
    speed = speed/20;
    var i = 100;
    var intervalId = setInterval(function() {
        if(i>=0) {
            thisE.style.opacity = i/100;
            thisE.style.filter = 'alpha(opacity='+i+')';
            i -= 5;
        } else {
            setTimeout(function() {thisE.style.display = "none";}, speed);
            clearInterval(intervalId);
            return false;
        }
    }, speed);
}
function fadeIn(thisId, speed) {
    var thisE = document.getElementById(thisId);
    thisE.style.display = "block";
    thisE.style.zoom = 1; //needed for IE
    thisE.style.opacity = 0;
    thisE.style.filter = "alpha(opacity = 0)";
    speed = speed/20;
    var i = 0;
    var intervalId = setInterval(function() {
        if(i <= 100) {
            thisE.style.opacity = i/100;
            thisE.style.filter = 'alpha(opacity='+i+')';
            i += 5;
        } else {
            clearInterval(intervalId);
            return false;
        }
    }, speed);
}

function check_answer(obj){
	
	obj.style.fontStyle = 'normal';
	obj.style.color = '#333';
	if(obj.value == 'Answer'){
		obj.value = '';
	}else if(obj.value == ''){
		obj.value = 'Answer';
		obj.style.color = '#999';
		obj.style.fontStyle = 'italic';
	}
		
}

// -------------------------------- popup functions -----------------------------------------------------

function toggle(div_id){
	var el=document.getElementById(div_id);
	if(el.style.display=='none'){
		el.style.display='block';
	}
	else{el.style.display='none';}
}
function blanket_size(popUpDivVar){
	if(typeof window.innerWidth!='undefined'){
		viewportheight=window.innerHeight;
	}
	else{
		viewportheight=document.documentElement.clientHeight;
	}
	if((viewportheight>document.body.parentNode.scrollHeight)&&(viewportheight>document.body.parentNode.clientHeight)){
		blanket_height=viewportheight;
	}
	else{
		if(document.body.parentNode.clientHeight>document.body.parentNode.scrollHeight){
			blanket_height=document.body.parentNode.clientHeight;
		}
		else{
			blanket_height=document.body.parentNode.scrollHeight;
		}
	}
	var blanket=document.getElementById('blanket');blanket.style.height=blanket_height+'px';
	var popUpDiv=document.getElementById(popUpDivVar);
	
	// 100 is half the height of the div
	popUpDiv_height=blanket_height/2-100;
	popUpDiv.style.top=230+'px';
}
function window_pos(popUpDivVar){
	if(typeof window.innerWidth!='undefined'){
		viewportwidth=window.innerHeight;
	}
	else{
		viewportwidth=document.documentElement.clientHeight;
	}
	if((viewportwidth>document.body.parentNode.scrollWidth)&&(viewportwidth>document.body.parentNode.clientWidth)){
		window_width=viewportwidth;
	}
	else{
		if(document.body.parentNode.clientWidth>document.body.parentNode.scrollWidth){
			window_width=document.body.parentNode.clientWidth;
		}
		else{
			window_width=document.body.parentNode.scrollWidth;
		}
	}
	//100 is half popup's width (see below)
	var popUpDiv=document.getElementById(popUpDivVar);window_width=window_width/2-110;
	popUpDiv.style.left=window_width+'px';
	popUpDiv.style.top=230+'px';
}
function popup(windowname){
	blanket_size(windowname);
	window_pos(windowname);
	toggle('blanket');
	toggle(windowname);
}

function isContactVaild(){
	var name = document.getElementById('full_name');
	var email = document.getElementById('email');
	var en = document.getElementById('enquiry');
	if(name.value == "" || name.value == "Please enter"){
		name.value = "Please enter";
		name.style.border = "1px solid red";
		name.style.color = 'red';
		return false;	
	}else if(email.value == "" || email.value == "Please enter"){
		email.value = "Please enter";
		email.style.border = "1px solid red";
		email.style.color = 'red';
		return false;	
	}else if(en.value == "" || en.value == "Please enter"){
		en.value = "Please enter";
		en.style.border = "1px solid red";
		en.style.color = 'red';
		return false;	
	}else {
		document.getElementById('submitID').value = 421;
		document.getElementById('contactForm').submit();
		return true;
	}
}
