var req;
var url;
function Initialize()
{
var req=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  req=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    req=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    req=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return req;
}

function ChooseLesson(key)
    {
    req = Initialize();
	var url="../components/lessonchooser.php?key="+key;
    if(req!=null)
    	{
		//window.alert("page doesn't exist!");
        req.onreadystatechange = ProcessLesson;
        req.open("GET", url, true);
        req.send(null);
    	}
	else alert("no ok")
	}

function ProcessLesson()
	{
    if(req.readyState == 4) 
        {
        // only if "OK"
            if (req.status == 200) 
            {
                if(req.responseText=="")
					{
                    //HideDiv("week");
					}
                else
                	{
                    //ShowDiv("week");
                    document.getElementById("lessonchooser").innerHTML =req.responseText;
                	}
           	 }
            else 
            	{
				document.getElementById("lessonchooser").innerHTML=
				"There was a problem retrieving data:<br>"+req.statusText;
            	}
        }
	}


function ChooseUnit(key)
    {
    req = Initialize();
	var url="../components/unitchooser.php?key="+key;
    if(req!=null)
    	{
		//window.alert("page doesn't exist!");
        req.onreadystatechange = ProcessUnit;
        req.open("GET", url, true);
        req.send(null);
    	}
	}

function ProcessUnit()
	{
    if(req.readyState == 4) 
        {
        // only if "OK"
            if (req.status == 200) 
            {
                if(req.responseText=="")
					{
                    //HideDiv("week");
					}
                else
                	{
                    //ShowDiv("week");
                    document.getElementById("unitchooser").innerHTML =req.responseText;
                	}
           	 }
            else 
            	{
				document.getElementById("unitchooser").innerHTML=
				"There was a problem retrieving data:<br>"+req.statusText;
            	}
        }
	}




function ChooseArea(key)
    {
    req = Initialize();
	var url="../components/areachooser.php?key="+key;
    if(req!=null)
    	{
		//window.alert("page doesn't exist!");
        req.onreadystatechange = ProcessArea;
        req.open("GET", url, true);
        req.send(null);
    	}
	}

function ProcessArea()
	{
    if(req.readyState == 4) 
        {
        // only if "OK"
            if (req.status == 200) 
            {
                if(req.responseText=="")
					{
                    //HideDiv("week");
					}
                else
                	{
                    //ShowDiv("week");
                    document.getElementById("areachooser").innerHTML =req.responseText;
                	}
           	 }
            else 
            	{
				document.getElementById("areachooser").innerHTML=
				"There was a problem retrieving data:<br>"+req.statusText;
            	}
        }
	}



function SendQuery(key)
    {
    Initialize();
	var url="http://www.phunkyfoods.co.uk/pages/weekchooser.php?key="+key;
    if(req!=null)
    	{
		/*window.alert("page doesn't exist!");*/
        req.onreadystatechange = Process;
        req.open("GET", url, true);
        req.send(null);
    	}
	}

function Process()
	{
    if(req.readyState == 4) 
        {
        // only if "OK"
            if (req.status == 200) 
            {
                if(req.responseText=="")
					{
                    //HideDiv("week");
					}
                else
                	{
                    //ShowDiv("week");
                    document.getElementById("weekchooser").innerHTML =req.responseText;
                	}
           	 }
            else 
            	{
				document.getElementById("weekchooser").innerHTML=
				"There was a problem retrieving data:<br>"+req.statusText;
            	}
        }
	}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function Store() {
	var links=document.getElementsByTagName("a");
	for(var i=0; i<links.length; i++) {
		if(links[i].className=="showreel") {
			links[i].onclick=function() {
				var newWin=window.open('showreel.php', 'title', 'width=400, height=300, scrollbars=1');
				newWin;
				return false;
			}
		}
		if(links[i].className=="storeOpen") {
			links[i].onclick=function() {
				var newWin=window.open('./store/home.html', 'title', 'width=850, height=700, scrollbars=1');
				newWin;
				return false;
			}
		}
		if(links[i].className=="storeOpen_ks1") {
			links[i].onclick=function() {
				var newWin=window.open('./store/index.php?page=basket&productid=10', 'title', 'width=850, height=700, scrollbars=1');
				newWin;
				return false;
			}
		}
		if(links[i].className=="storeOpen_ks2") {
			links[i].onclick=function() {
				var newWin=window.open('./store/index.php?page=basket&productid=11', 'title', 'width=850, height=700, scrollbars=1');
				newWin;
				return false;
			}
		}
		if(links[i].className=="healthopen") {
			links[i].onclick=function() {
				var newWin=window.open('./store/products-5.html', 'title', 'width=850, height=700, scrollbars=1');
				newWin;
				return false;
			}
		}
	}
}

 var b_timer = null; // blink timer
var b_on = true; // blink state
var blnkrs = null; // array of spans 

 function blink() {
var tmp = document.getElementsByTagName("span");
if (tmp) {
blnkrs = new Array();
var b_count = 0;
for (var i = 0; i < tmp.length; ++i) {
if (tmp[i].className == "blink") {
blnkrs[b_count] = tmp[i];
++b_count;
}
}
// time in m.secs between blinks
// 500 = 1/2 second
blinkTimer(500);
}
}

function blinkTimer(ival) {
if (b_timer) {
window.clearTimeout(b_timer);
b_timer = null;
}
blinkIt();
b_timer = window.setTimeout('blinkTimer(' + ival + ')', ival);
}

function blinkIt() {
for (var i = 0; i < blnkrs.length; ++i) {
if (b_on == true) {
blnkrs[i].style.visibility = "hidden";
}
else {
blnkrs[i].style.visibility = "visible";
}
}
b_on =!b_on;
}
//--> 



// jQuery
jQuery.noConflict();
jQuery(function()
{
	
	jQuery(".product_options").hide();
	jQuery("#programmes_fieldset input[name='programme_selection']").click(
		function ()
		{
			var selectedProgramme = jQuery(this).val();
			jQuery(".product_options").hide();
			jQuery("#product_options_fieldset").show();
			switch(selectedProgramme)
			{
				case "early":
					jQuery("#early_years").show();
					jQuery("#early_years input[type='radio']:first").attr("checked", true);
					break;
				case "special":
					jQuery("#special_needs").show();
					jQuery("#special_needs input[type='radio']:first").attr("checked", true);
					break;
				case "primary":
					jQuery("#primary_curriculum").show();
					jQuery("#primary_curriculum input[type='radio']:first").attr("checked", true);
					break;
			}
		});
	
	jQuery("#product_options_fieldset .product_options:last").show();
	jQuery("#product_options_fieldset .product_options:last input[type='radio']:first").attr("checked", true);
	
	jQuery("form").submit(function() 
		{
			
			var fields = jQuery(this).find(".mand");
			var invalid_count = 0;
			var formoutput = jQuery(this).find(".formoutput");
			var invalid_email = false;
			var show_invalid_email_warning = true;
			var cmsg = "The highlighted email address you provided does not seem to be correct. Would you like to continue anyway?";
			
			if(jQuery(formoutput).css("display") !== "none") {
				if(formoutput.length > 0) jQuery(formoutput).fadeOut(500);
			}
			
			for(i=0; i<fields.length; i++) {
				jQuery(fields[i]).removeClass("invalid_textfield");
			}
			
			for(i=0; i<fields.length; i++) {
				
				switch(fields[i].type) {
					case "select-one":
					case "select-multiple":
						if(fields[i].selectedIndex == 0) {
							jQuery(fields[i]).addClass("invalid_textfield");
							invalid_count++;
						}
						break;
					case "text":
					case "textarea":
					case "password":
						if(!fields[i].value) {
							jQuery(fields[i]).addClass("invalid_textfield");
							invalid_count++;
						} else {
							var name = jQuery(fields[i]).attr("name");
							if(name.indexOf("email") >= 0) {
								var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,4}){1,2}$/;
								if(emailRegxp.test(fields[i].value) == false) {
									invalid_email = true;
									if(show_invalid_email_warning) {
										jQuery(fields[i]).addClass("invalid_textfield");
									}
								}
							}
						}
						break;
				}
				
			}
			
			if( !invalid_count ) {
				
				if(invalid_email && show_invalid_email_warning) {
					if(!confirm(cmsg)) { 
						return false;
					}
				}
				return true;
				
			} else {
				
				if(formoutput.length > 0) {
					
					jQuery(formoutput).css("font-size", "0.9em");
					jQuery(formoutput).css("color", "#ff0000");
					jQuery(formoutput).css("font-weight", "bold");
					jQuery(formoutput).text("Please ensure the highlighted fields are complete before proceeding.");
					jQuery(formoutput).fadeIn(500);
					
				} else {
					
					alert("Please ensure the highlighted fields are complete before proceeding.");
					
				}
				
				return false;
				
			}
		
		}
	);
	
	jQuery("a.popup").click(
		function ()
		{
			var popup_href = jQuery(this).attr("href");
			var dimensions = String(jQuery(this).attr("rel")).split("|");
			var newWin=window.open(popup_href, '', 'width='+dimensions[0]+', height='+dimensions[1]+', scrollbars=1');
			newWin;
			return false;
		});
	
	jQuery("#navigation ul li ul").css("display", "none");
	jQuery("#navigation > ul > li > a").click(
		function ()
		{
			var child_ul = jQuery(this).parent().children("ul");
			var parent_li = jQuery(this).parent("li");
			//jQuery(child_ul).toggle();
			if(jQuery(child_ul).css("display") == "block") {
				jQuery(this).parent().addClass("itemselected");
			} else {
				jQuery(this).parent().removeClass("itemselected");
			}
			if(jQuery(this).parent().attr("class") !== "nosub") { 
				//return false;
			}
		});
	
	
	// This bit expands a parent menu if it's child is currently open.
	var currentPage = String(document.location.href);
	var slashpos = currentPage.lastIndexOf("/");
	currentPage = currentPage.substring(slashpos+1);
	
	jQuery("#navigation > ul > li > ul > li > a").each(
		function (i)
		{
			var thisObj = jQuery("#navigation > ul > li > ul > li > a:eq(" + i + ")");
			var thisObj_href = jQuery(thisObj).attr("href");
			if(currentPage.indexOf(thisObj_href) > -1) {
				jQuery(this).parent().parent().parent().addClass("selected");
				jQuery(thisObj).parent().parent().css("display", "block");
				jQuery(thisObj).css("font-weight", "bold");
				return false;
			}
		});
	
	jQuery("#navigation > ul > li > a").each(
		function (i)
		{
			var thisObj = jQuery("#navigation > ul > li > a:eq(" + i + ")");
			var thisObj_href = jQuery(thisObj).attr("href");
			if(currentPage.indexOf(thisObj_href) > -1) {
				jQuery(this).parent().addClass("itemselected");
				jQuery(this).parent().children().css("display", "block");
				jQuery(thisObj).css("font-weight", "bold");
				return false;
			}
		});
	
	if(currentPage == "teachers.html") {
		jQuery("#training_menu").parent().addClass("itemselected");
		jQuery("#training_menu").css("display", "block");
	}
	
	jQuery("#loginform input[name='username'], .loginboxes input[name='username']")
		.focus(function ()
			{
				var this_val = jQuery(this).val();
				if(this_val == "Username") {
					jQuery(this).val("");
				}
			})
		.blur(function ()
			{
				var this_val = jQuery(this).val();
				if(!this_val) {
					jQuery(this).val("Username");
				}
			});
	
	jQuery("#loginform input[name='password'], .loginboxes input[name='password']")
		.focus(function ()
			{
				var this_val = jQuery(this).val();
				if(this_val == "Password") {
					jQuery(this).val("");
				}
			})
		.blur(function ()
			{
				var this_val = jQuery(this).val();
				if(!this_val) {
					jQuery(this).val("Password");
				}
			});
	
});

jQuery(function()
	{
		
		
		jQuery("#cm_sc_2, #cm_sc_3, #cm_sc_4").parent().hide();
		
		jQuery("#cm_sc_4").change(
			function ()
			{
				//alert("hello");
			});
		
		jQuery("#lessonResults").hide();
		
		jQuery("#cm_sc_1, #cm_sc_2, #cm_sc_3").change(
			function ()
			{
				
				var formClass = jQuery(this).parent().parent().parent().attr("class");
				
				if(jQuery(this).val() == "resources") { 
					window.location.href = 'resources.html';
				}
				
				// Lesson results fieldset
				var lessonResults = jQuery("#lessonResults");
				
				// Work out which category level selected, and the next level.
				var thisCatLevel = parseInt(String(jQuery(this).attr("id")).substr(jQuery(this).attr("id").length-1));
				var nextCatLevel = thisCatLevel + 1;
				var nextCatObj = jQuery("#cm_sc_" + nextCatLevel);
				if(nextCatLevel >= 2) {
					jQuery("#cm_sc_" + (nextCatLevel+1)).parent().hide();
					jQuery("#cm_sc_" + (nextCatLevel+1)).empty().hide();
				}
				
				if(thisCatLevel == 3 || (thisCatLevel == 2 && (jQuery("#cm_sc_1").val() == 1639 || jQuery("#cm_sc_1").val() == 1648 || jQuery("#cm_sc_1").val() == 1670))) {
				
					jQuery(lessonResults).show();
					var cat_id = jQuery(this).val();
					if(formClass == "future") {
						var unitName = jQuery.ajax({type:"GET",url:"ajax.php",data:"action=getUnitName&id="+cat_id+"&future=1",async:false}).responseText;
					} else {
						var unitName = jQuery.ajax({type:"GET",url:"ajax.php",data:"action=getUnitName&id="+cat_id,async:false}).responseText;
					}
					jQuery(lessonResults).children("div.results").html("<p><strong>"+unitName+":</strong></p><p><img src=\"images/ajax-loading.gif\" align=\"absmiddle\" /> Loading lessons...</p>");
					
					if(formClass == "future") {
						var lessons = jQuery.ajax({type:"GET",url:"ajax.php",data:"action=getLessonsByUnit&id="+cat_id+"&future=1",async:false}).responseText;
					} else {
						var lessons = jQuery.ajax({type:"GET",url:"ajax.php",data:"action=getLessonsByUnit&id="+cat_id,async:false}).responseText;
					}
					jQuery(lessonResults).children("div.results").html("<p><strong>"+unitName+":</strong></p>"+lessons);
				
				}  else {
				
					jQuery(lessonResults).hide();
				
				}
				
				jQuery(nextCatObj).parent().hide();
				jQuery(nextCatObj).empty().hide();
				
				// Selected cat id.
				var thisCatId = jQuery(this).val();
				
				// Query categories table for a list of children of the selected category.
				if(formClass == "future") {
					var qryResult = jQuery.ajax({
												type: "GET",
												url: "ajax.php",
												data: "action=getChildCategories&id="+thisCatId+"&future=1",
												async: false
											}).responseText;
				} else {
					var qryResult = jQuery.ajax({
												type: "GET",
												url: "ajax.php",
												data: "action=getChildCategories&id="+thisCatId,
												async: false
											}).responseText;
				}
				var results = String(qryResult).split("|");
				var totalResults = results[0];
				
				if(totalResults > 0) {
					jQuery(nextCatObj).parent().show();
					jQuery(nextCatObj).show();
					if(thisCatId == 0) {
						
						jQuery(nextCatObj).parent().hide();
						jQuery(nextCatObj).empty().hide();
						
					} else {
						
						var blankOption = jQuery("<option>");
						jQuery(blankOption).val(0);
						jQuery(blankOption).html("Select a Category");
						jQuery(nextCatObj).append(blankOption);
						for(var i=1; i<=totalResults; i++) { 
							
							var category = results[i].split("=");
							var cmcat_id = category[0];
							var cmcat_title = category[1];
							
							var option = jQuery("<option>");
							jQuery(option).attr("value", cmcat_id);
							jQuery(option).html(cmcat_title);
							
							jQuery(nextCatObj).append(option);
							
						}
						
					}
				} else {
					jQuery(nextCatObj).parent().hide();
					jQuery(nextCatObj).hide();
				}
				
			});
	
	});

function blinkIt() {
	if (!document.all) return;
		else {
			for(i=0;i<document.all.tags('blink').length;i++){
				s=document.all.tags('blink')[i];
				s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
		}
	}
}



window.onload=function() { 

	blink();
	Store(); 
	
}