//config
function phoneFlash(status) {
	
	if (status == 'on') {
		var currentTime = new Date()
		var day = currentTime.getDate()
		var hour = currentTime.getHours()
		if ((hour > 9) && (hour < 17)) {
			if (document.getElementById('phoneStatus')) {
			
				var phoneStatus = document.getElementById('phoneStatus');
					phoneStatus.style.display = 'block';	
					
				} 
		}
	}
}

////////////////////////////////////////// START COOKIES ////////////////////////////////////////////

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				

////////////////////////////////////////// END COOKIES ////////////////////////////////////////////

// Adwords Phone Display

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return false;
  else
    return results[1];
}

function phoneNumSwitch ( state ) {

	if (state == 'on') {
		
		// is num set in ad
		
		// yes - set cookie
		
		// no - is a cookie set
		
		// yes - read cookie and use
		
		// no - ignore
		
		
	
		var num = gup( 'ad' );
		
		if (!num) {
			
			if (Get_Cookie( 'acsPhone' ) != '') { // there is a cookie value
					num = Get_Cookie( 'acsPhone' );
			} else {
				return;	
			}
		} 
		
		if (num) { // we have a num in url or cookie
			// set cookie
			Set_Cookie( 'acsPhone', num, '14', '/', '.ashburtoncookeryschool.co.uk' );
			
			//numbers list
			switch (num) {
				case '0':
					var newPhoneNum = '0843 289 5555';
					break;
				case '1':
					var newPhoneNum = '0843 289 9790';
					break;
				default:
					var newPhoneNum = '(01364) 652784';
			}
			
			// change numbers on page - look for span 'phoneNum')
			var spanArray = document.getElementsByTagName('span');
			
			for (i=0; i < spanArray.length; i++) { // loop through all spans to find phoneNums
				
				if (spanArray[i].className == 'phoneNum') {
				
					spanArray[i].innerHTML = newPhoneNum;
				
				}
			
			}
			
		}
		
	}

}
// End Phone Num Switch

function loadFlashMovie(url) {
	
	document.getElementById('photo').style.bgcolor = "#000000";
	
	var so = new SWFObject('/lib/js/mediaplayer/player.swf','mpl','368','262','9');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','true');
	so.addParam('play','true');
	so.addParam('scale','default');	
	so.addParam('bgcolor','#ffffff');
	so.addParam('flashvars','&file=' + url);
	so.write('photo');
	
	return;

}

 function courseFinder(action) {
 
	 var cfContainer = document.getElementById('cfContainer');
	 var cookeryNav = document.getElementById('cookeryNav');
	 var cookeryNavSpan = document.getElementById('cookeryNavSpan');
	
	 if (action == "show") {
	 
	 cfContainer.style.display = 'block';
	 cookeryNav.className = 'cookeryNavOver';
	 cookeryNavSpan.style.color = '#ffffff';
	
	 } else if (action == 'hide') {
	 
	  cfContainer.style.display = 'none';
	  cookeryNav.className = '';
	  cookeryNavSpan.style.color = '';
	 }
 
 return;
 }


function rand( min, max ) {
    if( max ) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    } else {
        return Math.floor(Math.random() * (min + 1));
    }
}

function reveal(elem,action) {
		var revealDiv = document.getElementById(elem);
		if (action == "show") {
			revealDiv.style.display = 'block';
		}
		if (action == "hide") {
			revealDiv.style.display = "none";
		}
	}
	
function Add2Cart(product_id)
{
	document.add_to_cart.product_id.value = product_id;
	document.add_to_cart.submit();
}

function cloneSelect(objid)
{
obj=document.getElementById(objid);
var sel=obj.cloneNode(true);
return sel;
}

function isValid(action)
{
		var selectMenu_courseDates = document.getElementById('productOptionsSelect_CourseDates');
		var selectMenuWrapper = document.getElementById('productOptionsSelectWrapper');
		var selectDupeWrapper = document.getElementById('menuDupe');
		
		var summary2 = document.getElementById('summary2');
		var summary = document.getElementById('summary');
		
		var attendeesValue = document.getElementById('Attendee');
		var attendeesDupe = document.getElementById('AttendeeDupe');
	
		var allergies = document.getElementById('Allergies');
		var allergiesDupe = document.getElementById('AllergiesDupe');
		
		//var accommodation = document.getElementById('Accommodation');
		//var accommodationDupe = document.getElementById('AccommodationDupe');
	
		if(action == 'order') {
			//alert(selectMenu_courseDates.options.length);
			
			if ((selectMenu_courseDates) && (selectMenu_courseDates.value == "Select Option")) {
		
				var label = document.getElementById('selectCourseDateLabel').innerHTML.split(':');
				
				alert('Please ' + label[0] + ' from the options listed');
				
				} else if (selectMenu_courseDates) {
				
				//open product options panel
				summary.style.display = 'none';
				summary2.style.display = 'block';
				
				selectMenu_courseDates.style.visibility = "hidden";
				
				//copy date across
				selectedDate = selectMenu_courseDates.selectedIndex;
				dateText = selectMenu_courseDates.options[selectedDate].text.split("[");
				selectDupeWrapper.innerHTML = dateText[0];
				
				//KITCHEN TEST
				dateSelected = selectDupeWrapper.innerHTML;
				dateSelected = dateSelected.replace('&amp;','and');
				product_id = document.getElementById('product_id').value;
				// run query to get kitchen
				var url = "/lib/inc/productOptionsKitchenTest.php?date="+dateSelected+'&product_id=' + product_id; // The server-side script
				http = getHTTPObject(); // We create the HTTP Object
				kitchenTest(url);
			
			} else {
				document.add_to_cart.submit();
			}
		
		} else if (action == 'back') {
			//hide product options panel
			summary2.style.display = 'none';
			summary.style.display = 'block';
			
			selectMenu_courseDates.style.visibility = "visible";
			
		} else if (action == 'process') {
	
			document.add_to_cart.submit();
			
		} else {
		document.add_to_cart.submit();
		}
}
	
// hack to move extra fields data around as i want it.
function loadData(string) {
	
var nameList =string.split(',');

for (i=0; i < nameList.length; i++) {
	
	var name = nameList[i];

	var value_spot = document.getElementById(name +'Value_spot');
	var head_spot = document.getElementById(name +'Head_spot');
	
	if (document.getElementById(name + 'Value')) {
	var value = document.getElementById(name + 'Value');
	var head = document.getElementById(name + 'Head');
	
		if(!value.innerHTML) {
		// remove superfluous divs
		value_spot.parentNode.removeChild(value_spot);
		head.parentNode.removeChild(head);
		} else {
			head_spot.innerHTML = head.innerHTML;
			value_spot.innerHTML = value.innerHTML;
			// remove superfluous divs
			head.parentNode.removeChild(head);
			value.parentNode.removeChild(value);
		}
	}
}
//hide kitchen field
if (document.getElementById('optionWrapperKitchen')) {
	document.getElementById('optionWrapperKitchen').style.display = 'none';
}

	// load up the skills value panel pop up data
	if (document.getElementById('skillLevelPanelValue')) {
	if (document.getElementById('skillLevelPanelValue').innerHTML != '') {
		document.getElementById('skillLevelPanel').innerHTML = document.getElementById('skillLevelPanelValue').innerHTML;
		document.getElementById('skillLevelPanelValue').innerHTML = '';
		}
	}
}

////////////////////////////////////////// PRODUCT OPTIONS HACK ///////////////////////////////////////////

function optionsHackResponse() {
  if (http.readyState == 4) {
 //alert(http.responseText);
			
    results = http.responseText.split('#'); // get the results from the php script and split them into chunks matching the product options
	
	for (i=0; i < results.length; i++) {
	
	 var moreResults = results[i].split("@"); // split up the output string into id, display string, inventory amount
	
	var counter = 0;
	
		for (e=0; e< moreResults.length; e++) {
				var newId = moreResults[0]; // this is the id of the rmenuItem
				//alert(newId);
				var newValue = moreResults[1]; // this is the new string to display in the select menu
	
				var newInventory = moreResults[2]; // this is the inventory amount
	
				if ((newId != '') && (newId != 'selectDate')) {
				//var target = document.getElementById(newId).parentNode.nextSibling.nextSibling;
				
				var target = document.getElementById(newId);
				target.innerHTML = newValue;
				
					if (newInventory == '0') {
						/* This block strikes through the option*/
						target.style.textDecoration = 'line-through';
						target.style.color = 'red';
						document.getElementById(newId).disabled = true;
						
					} else {
						counter++;
					}
				
				}
		}
	}

var selectMenu = document.getElementById('productOptionsSelect_CourseDates');
	 for (f = selectMenu.length-1; f>=0; f--) {// avoids strange results by looping down through options index
			if ((selectMenu.options[f]) && (selectMenu.options[f].innerHTML == 'old')) {
					selectMenu.remove(f);
			}
			
			
			///THIS REMOVES COURSE DATES WITH NO INVENTORY
			/*if (selectMenu.options[f].innerHTML.match("Sold")) {selectMenu.remove(f);}*/
	  }
	  
  }
}

function kitchenTestResponse() {
	var error = false;
	var debug = document.getElementById('debug');
	debug.innerHTML = '';
	
	  if (http.readyState == 4) {
		  
		  kitchen = http.responseText;
		  if (kitchen == 'error') {error = true;}
		  
		  debugOutput = 'responseText:'+kitchen+'<br>';
		  
		  // change the selected value of the kitchen
		  product_id = document.getElementById('product_id').value;
		  optionStr = product_id+'|Kitchen:'+kitchen;
		  
		  //alert (optionStr);
		  if (document.getElementById(optionStr)) {  
		 	 document.getElementById(optionStr).selected=true;
		  } else {
			error=true;  
		  }
		  
		  if (error) {
		  debugOutput += 'Select Value: '+document.getElementById('productOptionsSelect_Kitchen').value;
		  debug.innerHTML = debugOutput;
		  }
	  }
	
}

function updateProductOption(url) {
	if (document.getElementById('productOptionsSelect_CourseDates')) {
	
	var paramString = '';
	
   //var productOptionsTable = document.getElementById('productOptionsTable');  //radio
   //var productOptionsRadios = productOptionsTable.getElementsByTagName('input'); //radio
   
   var productOptionsTable = document.getElementById('productOptionsSelect_CourseDates'); //select
   var productOptionsRadios = productOptionsTable.getElementsByTagName('option'); // select
  
   for (i=0; i < productOptionsRadios.length; i++) {
  
	  var productOptionValue = productOptionsRadios[i].id + '@';
	  paramString += productOptionValue;
  
  }
	//alert(paramString);
	  http.open("GET", url + escape(paramString), true);
	  http.onreadystatechange = optionsHackResponse;
	  http.send(null);
	}
}

function kitchenTest(url) {
	  http.open("GET", url, true);
	  http.onreadystatechange = kitchenTestResponse;
	  http.send(null);
}

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function runProductOptionsHack(action) {
	if (action == 'on') {
		if (document.getElementById('selectCourseDateLabel')) {
			if (document.getElementById('selectCourseDateLabel').innerHTML == 'Select Course Date:&nbsp;') {
				var url = "/lib/inc/productOptionsHack.php?paramString="; // The server-side script
				http = getHTTPObject(); // We create the HTTP Object
				updateProductOption(url);
			}
		}
	}
}


function navStyle() {

if(window.location.href.match("https://")) {
// in ssl mode
	var getURL = window.location.href.split("https://www.");
} else {
	var getURL = window.location.href.split("http://www.");
}

var getURLclean = getURL[1];

var urlVars = getURLclean.split('/');

var strapline = document.getElementById('strapline');
var subStrapline = document.getElementById('subStrapline');
var header = document.getElementById('header');

var styleLoad = 'cookery';  // default styles to load

	/*// if there are no vars - assume at catalogue/home page
	if (urlVars.length == 1) {
	return;	
	}*/


	for (i=0; i < urlVars.length; i++) {
		var directory = urlVars[i];
		
		//alert(directory);
		
		if (directory.match("c_")) {
			// we have a category directory
			
			var category = directory.split('_');
			var categoryNum = category[1];
			
			
			switch(parseInt(categoryNum)) {
							case 60:  // cookery course catalogue home
							case 61: // 1 day courses
							case 62: // 2 day courses
							case 63:  // 5 day courses
							case 64: // Diploma
							case 87: // Special Offers
								header.style.background = 'url(/lib/images/images_header/banner' + rand(2,7) + '.jpg)';
								styleLoad = 'cookery';
								break;
							
							case 67:
							case 68:
							case 69:
							case 70:
							header.style.background = 'url(/lib/images/images_header/banner11.jpg)';
								styleLoad = 'store';
								break;
								
							case 66: // Wine School
							case 78:
							case 79:	
							case 80:
							case 85:
								header.style.background = 'url(/lib/images/images_header/banner10.jpg)';
								styleLoad = 'wine';
								break;
								
							default:
								header.style.background = 'url(/lib/images/images_header/banner1.jpg)';
								styleLoad = 'cookery';
								break;
			}
		} else if (directory.match("help")) {
			// we have a help category match
						header.style.background = 'url(/lib/images/images_header/banner20.jpg)';
						styleLoad = 'help';
		} else if (directory.match("checkout")) {
			// we have a help category match
						header.style.background = 'url(/lib/images/images_header/banner20.jpg)';
						styleLoad = 'help';
		} else if (directory.match("wine")) {
						header.style.background = 'url(/lib/images/images_header/banner10.jpg)';
						styleLoad = 'wine';
		} else if (directory.match("about")) {
						header.style.background = 'url(/lib/images/images_header/banner'+ rand(2,7) +'.jpg)';
						styleLoad = 'cookery';
		} else if (directory.match("about_ashburton.html")) {
						header.style.background = 'url(/lib/images/images_header/banner12.jpg)';
						styleLoad = 'accom';
		} else if (directory.match("accommodation_rooms.html")) {
						header.style.background = 'url(/lib/images/images_header/banner12.jpg)';
						styleLoad = 'accom';
		} else if (directory.match("giftvouchers")) {
						header.style.background = 'url(/lib/images/images_header/banner21.jpg)';
						styleLoad = 'gifts';
		}
	
	}
	
	// is it the home page?
if (getURLclean == "ashburtoncookeryschool.co.uk/") {
		var styleLoad = 'home';
}
	

switch (styleLoad) {
	
							case 'home':
							document.body.id = 'home';
							strapline.innerHTML = 'Ashburton Cookery School';
							subStrapline.innerHTML = "Inspirational Cookery Courses";
							break;
						
							case 'cookery':
							document.body.id = 'cookery';
							strapline.innerHTML = 'Ashburton Cookery School';
							subStrapline.innerHTML = "Inspirational Cookery Courses";
							break;
							
							case 'wine':
							document.body.id = 'wine';
							strapline.innerHTML = 'Ashburton Wine School';
							subStrapline.innerHTML = "Modern Wine Tasting and Wine Appreciation Courses";
							break;
							
							case 'accom':
							document.body.id = 'accom';
							strapline.innerHTML = 'Ashburton Court';
							subStrapline.innerHTML = "Quality B&B Rooms for Cookery School Students";
							break;
	
							case 'gifts':
							document.body.id = 'gifts';
							strapline.innerHTML = 'Gift Vouchers';
							subStrapline.innerHTML = "The perfect gift idea";
							break;
							
							case 'store':
							document.body.id = 'store';
							strapline.innerHTML = 'The Cookery Store';
							subStrapline.innerHTML = "Quality Cookware and Cooking Gifts";
							break;
						
							case 'help':
							document.body.id = 'help';
							strapline.innerHTML = 'Customer Service';
							subStrapline.innerHTML = "Call us on <span class='phoneNum'>(01364) 652784</span>";
							break;
							
							/*default:
							document.body.id = 'cookery';
							header.style.background = 'url(/lib/images/images_header/banner11.jpg)';
							strapline.innerHTML = 'Ashburton Cookery School';
							subStrapline.innerHTML = "Inspirational Cookery Courses";
							break;*/
						
						}
						
}

function msgBar() {

number = rand(0,1);

	if (number == 1) {
	
		document.getElementById('msgBar1').style.display = 'block';
		document.getElementById('msgBar2').style.display = 'none';
	
	}  else {
		
		document.getElementById('msgBar2').style.display = 'block';
		document.getElementById('msgBar1').style.display = 'none';
		
	}

}

function termsCheckHSBC() { // used in checkout
var termsCheckbox = document.getElementById('termsCheckbox');
	
	if (!termsCheckbox.checked) {
		alert('You must agree to our Cancellations Policy and Terms & Conditions before we can process your order.');	
		return false;
	} else {
		document.HSBC_form.submit();
		return true;
	}
	
}

function promoTrigger(action) {
	
	/* October Promo Trigger */
	if (action == 'on') {
			if (document.getElementById('durationValue_spot')) {
				var durationValue = document.getElementById('durationValue_spot');
				if ((durationValue.innerHTML == "5 Day") || (durationValue.innerHTML == "4 Weeks")) {
					 document.getElementById('octoberOfferBanner').style.display = "block";
				}
			}
	}
}

////////////////////////////////////////// FIRE FUNCTIONS///////////////////////////////////////////
function init() {
navStyle();
loadData('duration,times,level,offer,skills,recipes,rating,feedback,courseContent,tutor,comment');
runProductOptionsHack('on'); // turn the hack on or off
phoneNumSwitch('off'); // turn adwords phone switch on
promoTrigger('off');
phoneFlash('on');
}

window.onload = init;